溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

一個(gè)Servlet是怎么處理多個(gè)請(qǐng)求的

發(fā)布時(shí)間:2021-06-16 13:48:02 來源:億速云 閱讀:181 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)一個(gè)Servlet是怎么處理多個(gè)請(qǐng)求的的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

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的核心方法,每個(gè)servlet請(qǐng)求都會(huì)經(jīng)過此方法處理
    * @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("云過夢(mèng)無痕");
        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號(hào):" + 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標(biāo)記:" + 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){
            // 轉(zhuǎn)為json串
            String jsonStr = JSON.toJSONString(list);
            writer.write(jsonStr);
        } else {
            writer.write("查無數(shù)據(jù)!");
        }
    }
}

關(guān)注重點(diǎn)是service方法里的這些代碼:

一個(gè)Servlet是怎么處理多個(gè)請(qǐng)求的

然后jsp中的代碼如下:

一個(gè)Servlet是怎么處理多個(gè)請(qǐng)求的

可以看到一個(gè)共同點(diǎn),就是所有的a鏈接后面都帶有一個(gè)COMMAND參數(shù),只是綁定的值不一樣,就是根據(jù)這個(gè)綁定的值,來進(jìn)入到不同的業(yè)務(wù)方法中。

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  數(shù)據(jù)訪問層
 * @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

一個(gè)Servlet是怎么處理多個(gè)請(qǐng)求的

感謝各位的閱讀!關(guān)于“一個(gè)Servlet是怎么處理多個(gè)請(qǐng)求的”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI