简体   繁体   English

Java HttpServlet,重写方法服务,最佳实践

[英]Java HttpServlet, override method service, best practice

For logging purposes, I override the service method from HttpServlet like this: 为了进行记录,我像这样重写了HttpServlet的服务方法:

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
{
    logger.debug("enter servlet");
    logger.debug("Request Header: {}", MyHttpTools.requestHeaderToSting(req);

    super.service(req, resp);

    logger.debug("leaving servlet");
    logger.debug("Response Header: {}", MyHttpTools.responseHeaderToSting(resp);
}

I found some places in the web, where authors say "don't override service". 我在网上找到了一些地方,作者说“不要超越服务”。

What do you think of my approach? 您如何看待我的方法?

您的方法没有问题,但是您可以“更干净”的方式(在我看来),例如,通过实现(并注册) javax.servlet.Filter或使用AspectJ或其他更常用的方法。

Nothing inherently wrong with your approach. 您的方法天生没有错。

The authors are saying that don't override service() for business code, override the doPost() , doGet() etc. methods instead. 作者说不要重写业务代码的service() ,而是重写doPost()doGet()等方法。

Your approach is correct. 您的方法是正确的。 You can do logging with aspectJ too. 您也可以使用AspectJ进行日志记录。

The default service() method in an HTTP servlet routes the request to another method based on the HTTP transfer method (POST, GET, and so on). HTTP Servlet中的默认service()方法基于HTTP传输方法(POST,GET等)将请求路由到另一个方法。 For example, HTTP POST requests are routed to the doPost() method, HTTP GET requests are routed to the doGet() method, and so on. 例如,HTTP POST请求被路由到doPost()方法,HTTP GET请求被路由到doGet()方法,依此类推。 This enables the servlet to perform different request data processing depending on the transfer method. 这使Servlet能够根据传输方法执行不同的请求数据处理。 Since the routing takes place in service(), there is no need to generally override service() in an HTTP servlet . 由于路由发生在service()中,因此通常无需在HTTP servlet中覆盖service() Instead, override doGet(), doPost(), and so on, depending on the expected request type. 而是根据期望的请求类型重写doGet(),doPost()等。

For detail plz go through this article : Sun Java System Web Server 6.1 SP6 Programmer's Guide to Web Applications 有关详细信息,请阅读本文: Sun Java System Web Server 6.1 SP6 Web应用程序程序员指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM