一個Servlet是如何處理多個請求的?

1、servlet層

package com.ycz.controller;

import com.alibaba.fastjson.JSON;
import com.ycz.dao.PeopleDao;
import com.ycz.domain.People;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Description
 * @ClassName MyServlet
 * @Author yanchengzhi
 * @date 2021.06.06 20:16
 */
public class MyServlet extends HttpServlet {

    PeopleDao peopleDao = new PeopleDao();

    /*
    * @description: servlet的核心方法,每個servlet請求都會經過此方法處理
    * @param: [req, res]
    * @return: void
    * @author: yanchengzhi
    * @date: 2021/6/14 10:52
    */
    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        String command = request.getParameter("COMMAND");
        if("ADD".equals(command)) {
            addPeople(request,response);
            return;
        }
        if("UPDATE".equals(command)){
            updatePeople(request,response);
            return;
        }
        if("DEL".equals(command)) {
            deletePeople(request,response);
            return;
        }
        if("FIND".equals(command)) {
            findById(request,response);
            return;
        }
        if("FINDALL".equals(command)) {
            findAll(request,response);
            return;
        }
    }

    /*
    * @description: 添加
    * @param: [request, response]
    * @return: void
    * @author: yanchengzhi
    * @date: 2021/6/14 10:51
    */
    private void addPeople(HttpServletRequest request,HttpServletResponse response) throws IOException {
        People people = new People();
        people.setName("雲過夢無痕");
        people.setBirth(new Date());
        people.setTag(0);
        response.setContentType("text/html;charset=utf-8");
        //response.setContentType("text/plain; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        int res = peopleDao.addPeople(people);
        if(res > 0){
            writer.write("<h2>添加成功!</h2>");
        } else {
            writer.write("<h2>添加失敗!</h2>");
        }
        writer.flush();
        writer.close();
    }


    /*
    * @description: 修改
    * @param: [request, response]
    * @return: void
    * @author: yanchengzhi
    * @date: 2021/6/14 10:54
    */
    private void updatePeople(HttpServletRequest request,HttpServletResponse response) throws IOException {
        // 獲取修改記錄的id
        Integer id = Integer.parseInt(request.getParameter("id"));
        People p = new People();
        p.setName("yanchengzhi");
        Calendar calendar = Calendar.getInstance();
        calendar.set(1995,9,18);
        Date date = calendar.getTime();
        p.setBirth(date);
        int res = peopleDao.updatePeople(p,id);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if(res > 0){
            writer.write("<h2>修改成功!</h2>");
        } else {
            writer.write("<h2>修改成功!</h2>");
        }
        writer.flush();
        writer.close();
    }
    
    /*
    * @description: 刪除記錄
    * @param: [request, response]
    * @return: void
    * @author: yanchengzhi
    * @date: 2021/6/14 12:15
    */
    private void deletePeople(HttpServletRequest request,HttpServletResponse response) throws IOException{
        Integer id = Integer.parseInt(request.getParameter("id"));
        int res = peopleDao.delPeople(id);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if(res > 0) {
            writer.write("<h2>刪除成功!</h2>");
        } else {
            writer.write("<h2>刪除失敗!</h2>");
        }
        writer.flush();
        writer.close();
    }

    /*
    * @description: 按照id查詢
    * @param: [request, response]
    * @return: void
    * @author: yanchengzhi
    * @date: 2021/6/14 14:20
    */
    private void findById(HttpServletRequest request,HttpServletResponse response) {
        Integer id = Integer.parseInt(request.getParameter("id"));
        People p = peopleDao.findById(id);
        if(p != null) {
            System.out.println("查找的記錄信息如下:");
            System.out.println("-------------------");
            System.out.println("Id號:" + p.getId());
            System.out.println("姓名:" + p.getName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            System.out.println("生日:" + sdf.format(p.getBirth()));
            System.out.println("Tag標記:" + p.getTag());
        } else {
            System.out.println("查詢的記錄不存在!");
        }
    }

    private void findAll(HttpServletRequest request,HttpServletResponse response) throws IOException{
        List<People> list = peopleDao.findAll();
        response.setContentType("text/plain;charset=utf-8");
        PrintWriter writer = response.getWriter();
        if(list != null && list.size() > 0){
            // 轉為json串
            String jsonStr = JSON.toJSONString(list);
            writer.write(jsonStr);
        } else {
            writer.write("查無數據!");
        }
    }
}

關註重點是service方法裡的這些代碼:

在這裡插入圖片描述

然後jsp中的代碼如下:

在這裡插入圖片描述

可以看到一個共同點,就是所有的a鏈接後面都帶有一個COMMAND參數,隻是綁定的值不一樣,就是根據這個綁定的值,來進入到不同的業務方法中。

2、dao層代碼

package com.ycz.dao;

import com.ycz.conf.DataSourceManager;
import com.ycz.domain.People;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description  數據訪問層
 * @ClassName PeopleDao
 * @Author yanchengzhi
 * @date 2021.06.08 08:50
 */
public class PeopleDao {


    /*
    * @description: 添加
    * @param: [people]
    * @return: int
    * @author: yanchengzhi
    * @date: 2021/6/14 11:03
    */
    public int addPeople(People people){
        int res = 0;
        String sql = "insert into people (name,birth,tag) values (?,UNIX_TIMESTAMP(?),?)";
        Connection connection = DataSourceManager.getConnection();
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1,people.getName());
            ps.setDate(2,new Date(people.getBirth().getTime()));
            ps.setInt(3,people.getTag());
            res = ps.executeUpdate();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            DataSourceManager.closeConnection(connection);
            DataSourceManager.closeStatement(ps);
        }
        return res;
    }

    /*
    * @description: 修改
    * @param: [p, id]
    * @return: int
    * @author: yanchengzhi
    * @date: 2021/6/14 11:03
    */
    public int updatePeople(People p, Integer id) {
        int res = 0;
        String sql = "update people set name = ?,birth = UNIX_TIMESTAMP(?) where id = ?";
        Connection connection = DataSourceManager.getConnection();
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1,p.getName());
            ps.setDate(2,new Date(p.getBirth().getTime()));
            ps.setInt(3,id);
            res = ps.executeUpdate();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            DataSourceManager.closeConnection(connection);
            DataSourceManager.closeStatement(ps);
        }
        return res;
    }

    /*
    * @description: 刪除
    * @param: [id]
    * @return: int
    * @author: yanchengzhi
    * @date: 2021/6/14 12:20
    */
    public int delPeople(Integer id) {
        int res = 0;
        String sql = "delete from people where id = ?";
        Connection connection = DataSourceManager.getConnection();
        PreparedStatement ps = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1,id);
            res = ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataSourceManager.closeConnection(connection);
            DataSourceManager.closeStatement(ps);
        }
        return res;
    }

    /*
    * @description: 按照id查詢
    * @param: [id]
    * @return: com.ycz.domain.People
    * @author: yanchengzhi
    * @date: 2021/6/14 14:20
    */
    public People findById(Integer id) {
        String sql = "select id,name,FROM_UNIXTIME(birth) birthday,tag from people where id = ?";
        Connection connection = DataSourceManager.getConnection();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setInt(1,id);
            resultSet = ps.executeQuery();
            while(resultSet.next()){
                People p = new People();
                p.setId(resultSet.getInt("id"));
                p.setName(resultSet.getString("name"));
                p.setBirth(resultSet.getDate("birthday"));
                p.setTag(resultSet.getInt("tag"));
                return p;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataSourceManager.closeConnection(connection);
            DataSourceManager.closeStatement(ps);
            DataSourceManager.closeResultSet(resultSet);
        }
        return null;
    }

    /*
    * @description: 查詢所有記錄
    * @param: []
    * @return: java.util.List<com.ycz.domain.People>
    * @author: yanchengzhi
    * @date: 2021/6/14 14:43
    */
    public List<People> findAll() {
        List<People> peoples = new ArrayList<>();
        String sql = "select id,name,FROM_UNIXTIME(birth) birthday,tag from people";
        Connection connection = DataSourceManager.getConnection();
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        try {
            ps = connection.prepareStatement(sql);
            resultSet = ps.executeQuery();
            while(resultSet.next()){
                People p = new People();
                p.setId(resultSet.getInt("id"));
                p.setName(resultSet.getString("name"));
                p.setBirth(resultSet.getDate("birthday"));
                p.setTag(resultSet.getInt("tag"));
                peoples.add(p);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataSourceManager.closeConnection(connection);
            DataSourceManager.closeStatement(ps);
            DataSourceManager.closeResultSet(resultSet);
        }
        return peoples;
    }
}

3、web.xml

在這裡插入圖片描述

到此這篇關於一個Servlet是如何處理多個請求的?的文章就介紹到這瞭,更多相關Servlet處理多個請求內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: