覆盖HttpServlet服务方法

时间:2012-12-15 12:00:55

标签: java-ee tomcat servlets

我有一个看起来像这样的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()

但我想知道这是否会制造任何问题或导致任何问题。

2 个答案:

答案 0 :(得分:23)

这是service()通常实施的方式(very simplified):

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()。因此,用doGet()替换doPost()service()就可以了。另一方面,您的servlet还将处理PUTDELETEHEAD和其他方法,而单独的doGet()doPost()将返回 405方法不允许

这就是为什么我实际上建议将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(.....);

}

答案 1 :(得分:9)

你最好保持原样。覆盖service()方法也会使此方法回答PUT,HEAD,DELETE等。它绕过了默认service()方法对上次修改的标题所做的工作。