HTTPServlet可以不重写Service方法的原因

释放双眼,带上耳机,听听看~!

序言

当我们继承HttpServlet类的时候,其实我们只需要重写servlet中的doGet方法,和doPost方法,无需再进行重写service方法。

打开httpservlet的源码文件,查看大概在第658行处service函数的定义,在这里可以看到service函数无论如何最终都是要进行doGet或者是doPost的调用,所以我们在继承Httpservlet类的时候,可以直接对doGet和doPost进行重写

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

测试

创建客户端提交表单

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <form action="http://localhost:8080/Demo_03/my_http_servlet" method="get">
            ID:<input type="text" name="IdNumber">
            Pw:<input type="password" name="pw">
            使用get方法提交<input type="submit" name = "GetSubmit">
        </form>
        </br>
        <form action="http://localhost:8080/Demo_03/my_http_servlet" method="post">
            ID:<input type="text" name="IdNumber">
            Pw:<input type="password" name="pw">
            使用get方法提交<input type="submit" name = "GetSubmit">
        </form>
    </body>
</html>

创建对应类

package com.demo03_httpServlet;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class MyHttpServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String MethodName = req.getMethod();
        System.out.println("当前使用的请求方法:" + MethodName);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String MethodName = req.getMethod();
        System.out.println("当前使用的请求方法:" + MethodName);
    }




}

配置文件

<!-- HttpServlet获取请求的演示 -->
  
  <servlet>
      <servlet-name>MyHttpServlet</servlet-name>
      <servlet-class>com.demo03_httpServlet.MyHttpServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>MyHttpServlet</servlet-name>
      <url-pattern>/my_http_servlet</url-pattern>
  </servlet-mapping>

运行测试

给TA买糖
共{{data.count}}人
人已赞赏
知识分享

Servlet的生命周期

2020-9-21 22:59:00

知识分享

WordPress网站加装SSL证书后无法正常加载图片

2020-9-22 23:04:00

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索