问题
Are jsp PageContext objects created and destroyed as part of the http request-response cycle or are they cached and reused between requests.
PageContext has life-cycle methods that suggest reuse between requests. ie initialize(), release().
If they are reused this could pose serious concurrency problems: if two http requests arrive, requesting the same jsp page, and each request is processed by its own thread, but sets attributes on a shared PageContext object, they will render each others' content.
Any help appreciated. By the way I am using the servlet container embedded in Apache Sling.
回答1:
PageContext are only available from your JSP page. If your request was first handled by the servlet, and then forwarded to JSP page (using RequestDispatcher.forward), pageContext is only available on this JSP page, but there is no way to access it from the servlet (because there was no pageContext yet at that time).
From JSP page point of view, it is getting new pageContext every time it is called. Page contexts may be pooled internally, but not shared by multiple JSP pages at the same time.
initialize
and release
methods have this comment: "This method should not be used by page or tag library authors." Just forget about them.
回答2:
Peter is correct. The PageContext
is provisioned for the scope of processing a page. Consumers should not keep a reference to these instances outside this scope which implicitly means instances shouldn't be accessible outside the current thread.
Example JSP processing code from the JSP 2.2 specification:
public class foo implements Servlet {
// ...
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
JspFactory factory = JspFactory.getDefaultFactory();
PageContext pageContext = factory.getPageContext(
this,
request,
response,
null, // errorPageURL
false, // needsSession
JspWriter.DEFAULT_BUFFER,
true // autoFlush
);
// initialize implicit variables for scripting env ...
HttpSession session = pageContext.getSession();
JspWriter out = pageContext.getOut();
Object page = this;
try {
// body of translated JSP here ...
} catch (Exception e) {
out.clear();
pageContext.handlePageException(e);
} finally {
out.close();
factory.releasePageContext(pageContext);
}
}
How the PageContext
instance is provisioned (from pools or instance creation) is an implementation detail of the container.
来源:https://stackoverflow.com/questions/9581227/what-is-the-lifecycle-of-a-jsp-pagecontext-object-is-it-threadsafe