• Servlet学习(三):HttpServlet


    1、入门

    编写一个Servlet就必须要实现Servlet接口,重写接口中的5个方法,虽然已经能完成要求,但是编写起来还是比较麻烦的,因为我们更关注的其实只有service方法,那有没有更简单方式来创建Servlet呢?

    要想解决上面的问题,我们需要先对Servlet的体系结构进行下了解:

    在这里插入图片描述

    因为我们将来开发B/S架构的web项目,都是针对HTTP协议,所以我们自定义Servlet,会通过继承HttpServlet

    具体的编写格式如下:

    @WebServlet("/demo4")
    public class ServletDemo4 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //TODO GET 请求方式处理逻辑
            System.out.println("get...");
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //TODO Post 请求方式处理逻辑
            System.out.println("post...");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、详解

    1. HttpServlet中为什么要根据请求方式的不同,调用不同的方法?
    2. 如何调用?

    针对问题一,我们需要回顾之前的知识点前端发送GET和POST请求的时候,参数的位置不一致,GET请求参数在请求行中,POST请求参数在请求体中,为了能处理不同的请求方式,我们得在service方法中进行判断,然后写不同的业务处理,这样能实现,但是每个Servlet类中都将有相似的代码,针对这个问题,有什么可以优化的策略么?

    @WebServlet("/demo5")
    public class ServletDemo5 implements Servlet {
    
        public void init(ServletConfig config) throws ServletException {
    
        }
    
        public ServletConfig getServletConfig() {
            return null;
        }
    
        public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
            //如何调用?
            //获取请求方式,根据不同的请求方式进行不同的业务处理
            HttpServletRequest request = (HttpServletRequest)req;
           //1. 获取请求方式
            String method = request.getMethod();
            //2. 判断
            if("GET".equals(method)){
                // get方式的处理逻辑
            }else if("POST".equals(method)){
                // post方式的处理逻辑
            }
        }
    
        public String getServletInfo() {
            return null;
        }
    
        public void destroy() {
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    要解决上述问题,我们可以对Servlet接口进行继承封装,来简化代码开发。

    package com.itheima.web;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import java.io.IOException;
    
    public class MyHttpServlet implements Servlet {
        public void init(ServletConfig config) throws ServletException {
    
        }
    
        public ServletConfig getServletConfig() {
            return null;
        }
    
        public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
            HttpServletRequest request = (HttpServletRequest)req;
            //1. 获取请求方式
            String method = request.getMethod();
            //2. 判断
            if("GET".equals(method)){
                // get方式的处理逻辑
                doGet(req,res);
            }else if("POST".equals(method)){
                // post方式的处理逻辑
                doPost(req,res);
            }
        }
    
        protected void doPost(ServletRequest req, ServletResponse res) {
        }
    
        protected void doGet(ServletRequest req, ServletResponse res) {
        }
    
        public String getServletInfo() {
            return null;
        }
    
        public void destroy() {
    
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    有了MyHttpServlet这个类,以后我们再编写Servlet类的时候,只需要继承MyHttpServlet,重写父类中的doGet和doPost方法,就可以用来处理GET和POST请求的业务逻辑。接下来,可以把ServletDemo5代码进行改造

    @WebServlet("/demo5")
    public class ServletDemo5 extends MyHttpServlet {
    
        @Override
        protected void doGet(ServletRequest req, ServletResponse res) {
            System.out.println("get...");
        }
    
        @Override
        protected void doPost(ServletRequest req, ServletResponse res) {
            System.out.println("post...");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    将来页面发送的是GET请求,则会进入到doGet方法中进行执行,如果是POST请求,则进入到doPost方法。这样代码在编写的时候就相对来说更加简单快捷。

    类似MyHttpServlet这样的类Servlet中已经为我们提供好了,就是HttpServlet,翻开源码,大家可以搜索service()方法,你会发现HttpServlet做的事更多,不仅可以处理GET和POST还可以处理其他五种请求方式。

    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
        {
            String method = req.getMethod();
    
            if (method.equals(METHOD_GET)) {
                long lastModified = getLastModified(req);
                if (lastModified == -1) {
                    // servlet doesn't support if-modified-since, no reason
                    // to go through further expensive logic
                    doGet(req, resp);
                } else {
                    long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                    if (ifModifiedSince < lastModified) {
                        // If the servlet mod time is later, call doGet()
                        // Round down to the nearest second for a proper compare
                        // A ifModifiedSince of -1 will always be less
                        maybeSetLastModified(resp, lastModified);
                        doGet(req, resp);
                    } else {
                        resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    }
                }
    
            } else if (method.equals(METHOD_HEAD)) {
                long lastModified = getLastModified(req);
                maybeSetLastModified(resp, lastModified);
                doHead(req, resp);
    
            } else if (method.equals(METHOD_POST)) {
                doPost(req, resp);
                
            } else if (method.equals(METHOD_PUT)) {
                doPut(req, resp);
                
            } else if (method.equals(METHOD_DELETE)) {
                doDelete(req, resp);
                
            } else if (method.equals(METHOD_OPTIONS)) {
                doOptions(req,resp);
                
            } else if (method.equals(METHOD_TRACE)) {
                doTrace(req,resp);
                
            } else {
                //
                // Note that this means NO servlet supports whatever
                // method was requested, anywhere on this server.
                //
    
                String errMsg = lStrings.getString("http.method_not_implemented");
                Object[] errArgs = new Object[1];
                errArgs[0] = method;
                errMsg = MessageFormat.format(errMsg, errArgs);
                
                resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
  • 相关阅读:
    计算机专业毕业设计项目推荐03-Wiki系统设计与实现(JavaSpring+Vue+Mysql)
    [附源码]java毕业设计望湘人电子商城
    进程之理解进程的概念
    校园邮箱-注册
    Pytorch 基于LeNet的手写数字识别
    Java对指定不规则的jsonString读取并操作
    【11】二进制编码:“手持两把锟斤拷,口中疾呼烫烫烫”?
    [JS真好玩] 掘金创作者必备: 用一行JS查看所有文章的转化率,让你知道什么标题才是好标题
    Java实现堆算法
    [TUCTF 2022] 部分
  • 原文地址:https://blog.csdn.net/john1516/article/details/126843437