一个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("

添加成功!

"); } else { writer.write("

添加失败!

"); } 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("

修改成功!

"); } else { writer.write("

修改成功!

"); } 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("

删除成功!

"); } else { writer.write("

删除失败!

"); } 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 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方法里的这些代码:

一个Servlet是如何处理多个请求的?_第1张图片

然后jsp中的代码如下:

一个Servlet是如何处理多个请求的?_第2张图片

可以看到一个共同点,就是所有的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
    * @author: yanchengzhi
    * @date: 2021/6/14 14:43
    */
    public List findAll() {
        List 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是如何处理多个请求的?_第3张图片

到此这篇关于一个Servlet是如何处理多个请求的?的文章就介绍到这了,更多相关Servlet处理多个请求内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(一个Servlet是如何处理多个请求的?)