What is a life of HttpServletRequest object?

2020-06-18 09:44发布

I have doubt about HttpServletRequest life object. Is the request object destroyed after it got into controller?

1条回答
家丑人穷心不美
2楼-- · 2020-06-18 10:23

The lifetime of an HttpServletRequest object is just that: the time of serving an HTTP Servlet request.

It may be created right before calling the servlet's doGet(), doPost() etc. methods, and may be destroyed right after that. It is only valid to use it during serving a request.

Note: However Servlet containers may reuse HttpServletRequest objects for multiple requests (and this is typically the case), but they will be "cleaned" or reset so no objects (like parameters or attributes) will leak between requests. This is simply due to performance issue: it is much faster and cheaper to reset an HttpServletRequest object than to throw away an existing one and create a new one.

In a typical Servlet container implementation if an HTTP request comes in, an HttpServletRequest is created right when the HTTP input data of the request is parsed by the Servlet container. The whole request might be lazily initialized (e.g. parameters might only be parsed and populated if they are really accessed e.g. via getParameter() method). Then this HttpServletRequest (which extends ServletRequest) is passed through the Servlet filters and then passed on to Servlet.service() which will dispatch the call to doGet(), doPost() etc based on the HTTP method (GET, POST, PUT etc.). Then the request will still be alive until the request-response pair cycles back throughout the filter chain. And then it will be destroyed or reset (before it is used for another HTTP request).

查看更多
登录 后发表回答