温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

一个Servlet是怎么处理多个请求的

发布时间:2021-06-16 13:48:02 来源:亿速云 阅读:183 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关一个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("<h3>添加成功!</h3>");
        } else {
            writer.write("<h3>添加失败!</h3>");
        }
        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("<h3>修改成功!</h3>");
        } else {
            writer.write("<h3>修改成功!</h3>");
        }
        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("<h3>删除成功!</h3>");
        } else {
            writer.write("<h3>删除失败!</h3>");
        }
        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方法里的这些代码:

一个Servlet是怎么处理多个请求的

然后jsp中的代码如下:

一个Servlet是怎么处理多个请求的

可以看到一个共同点,就是所有的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是怎么处理多个请求的”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI