Java 什么是 HttpServlet 类中的“服务”方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30550189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:48:15  来源:igfitidea点击:

What is 'service' method in HttpServlet class?

javaservlets

提问by overexchange

Below is a simple servlet written for learning.

下面是一个为学习而编写的简单servlet。

package com.example.tutorial;

import java.io.IOException;
import java.io.PrintWriter;

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


public class ServletExample extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("Hello Java!");
    }

}

When a browser hits this URI: http://localhost:8081/ServletsJSPExample/servletexample,

当浏览器访问这个网址:http://localhost:8081/ServletsJSPExample/servletexample

By analyzing the request header of http packet, it shows GETrequest sent from the browser. But, In my servlet, I do not have GETrequest to process.

通过解析http包的请求头,可以看出GET浏览器发送的请求。但是,在我的 servlet 中,我没有GET要处理的请求。

So,

所以,

When does servicemethod gets invoked?

什么时候service调用方法?

Why does servicemethod receives this GETrequest?

为什么service方法会收到这个GET请求?

采纳答案by Sotirios Delimanolis

HttpServletimplements Servletwhose servicemethod javadocstates

HttpServlet实现Servletservice方法 javadoc声明

Called by the servlet container to allow the servlet to respond to a request.

由 servlet 容器调用以允许 servlet 响应请求。

This is the entry point of all Servlet handling. The Servlet container instantiates your Servletclass and invokes this method on the generated instance if it determines that your Servletshould handle a request.

这是所有 Servlet 处理的入口点。Servlet 容器实例化您的Servlet类并在生成的实例上调用此方法(如果它确定您Servlet应该处理请求)。

HttpServletis an abstractclass which implementsthis method by delegating to the appropriate doGet, doPost, doXyzmethods, depending on the HTTP method used in the request.

HttpServletabstract哪一个类实现通过委托给适当的这种方法doGetdoPostdoXyz方法,根据在请求中使用的HTTP方法。

@Override
public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException
{
    HttpServletRequest  request;
    HttpServletResponse response;

    if (!(req instanceof HttpServletRequest &&
            res instanceof HttpServletResponse)) {
        throw new ServletException("non-HTTP request or response");
    }

    request = (HttpServletRequest) req;
    response = (HttpServletResponse) res;

    service(request, response);
}
[...]
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);
    }
}

If you override the servicemethod from HttpServlet, you lose that behavior and revert back to a single handling of all Servlet requests.

如果您覆盖service方法HttpServlet,您将失去该行为并恢复到对所有 Servlet 请求的单一处理。