Monday, August 9, 2010

Using and Understanding PageContext in JSP

PageContext is an abstract class which extends javax.servlet.jsp.JspContext, it provides context information when JSP is used in servlet environment, it is obtained by calling JspFactory.getPageContext(), and released by calling JspFactory.releasePageContext().

PageContext provides a single API to access various scope namespaces. Obtains an instance of an implementation dependent javax.servlet.jsp.PageContext abstract class for the calling Servlet and currently pending request and response.

JspFactory.getPageContext() is typically called early in the processing of the _jspService() method of a JSP implementation class in order to obtain a PageContext object for the request being processed.

Invoking this method shall result in the PageContext.initialize() method being invoked. The PageContext returned is properly initialized.

All PageContext objects obtained via this method shall be released by invoking releasePageContext().

Signature:

public abstract PageContext getPageContext(Servlet servlet,
ServletRequest request,
ServletResponse response,
String errorPageURL,
boolean needsSession,
int buffer,
boolean autoflush)

Example:

public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {

PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;


try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();

For every request, there will be one PageContext instance created and populated properly( various scope values)

Before the _jspService() method return, it will invoke JspFactory.releasePageContext() method, results in the PageContext.release()

method is invoked.

...

} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}

Posted via email from Progress