16

我有一个 servlet,它看起来像:

public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
    doTheJob(request, response);
}//method doGet

public void doPost(HttpServletRequest request, HttpServletResponse response)
              throws IOException, ServletException {
    doTheJob(request, response);
}//method doPost

private void doTheJob(.....) {
    ...........................
}

}

由于我的应用程序的工作方式,我只需要从doGet()doPost()调用doTheJob( ) 。所以我认为,我最好覆盖HttpServlet的方法service()

但我想知道这是否会阻碍任何事情或会导致任何问题。

4

2 回答 2

24

这就是service()通常的实现方式(非常简化):

protected void service(HttpServletRequest req, HttpServletResponse resp) {
    String method = req.getMethod();

    if (method.equals(METHOD_GET)) {
            doGet(req, resp);
    } else if (method.equals(METHOD_HEAD)) {
        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 {
        resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
    }
}

正如你所看到的,它几乎没有委托给HTTP 方法doGet()doPost()依赖于 HTTP 方法。所以从一只手上替换doGet()doPost()service()就可以了。另一方面,您的 servlet 也将处理单独PUT的、、和其他方法,DELETE它将返回405 Method not allowedHEADdoGet()doPost()

这就是为什么我实际上建议将代码分开doGet()doPost()委托给您的代码,并让 servlet 处理其他方法。如果这是您的代码中重复出现的模式,请考虑以下帮助 servlet:

public class AbstractServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
                 throws IOException, ServletException {
        doGetOrPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
                  throws IOException, ServletException {
        doGetOrPost(request, response);
    }

    abstract protected void doGetOrPost(.....);

}
于 2012-12-15T12:09:00.493 回答
9

你最好保持原样。覆盖该service()方法还会使该方法响应 PUT、HEAD、DELETE 等。它绕过了默认service()方法对最后修改的标头所做的工作。

于 2012-12-15T12:09:30.147 回答