obtain reference to JspContext/PageContext from a servlet

12,910

Solution 1

Let me see if I understood: you want to invoke a JSP from a servlet and make some variables (which are under the control of the servlet) available to the JSP. Right?

Then forget about the PageContext, it's just specific to JSP pages and it can't be accessed from a servlet. Any attribute you set in the request, session or servlet context will be available in the JSP. The PageContext is a scope wider than the previous ones and it comes with a findAttribute method that, when invoked, will look for an attribute with given name inside the page's context, request, session or servlet context (in that order).

So, the only thing you need is to set those variables as attributes in one of those scopes, I would suggest to use the request one (HttpServletRequest.setAttribute("foo", "fooValue")) and then use it in your JSP using a value expression (${foo}).

Solution 2

You should use request scope. A pageContext is obtained by a implementation dependent subclass of JspFactory in the service method of the JSP. In Tomcat, for example

public void _jspService(
 ...
pageContext = _jspxFactory.getPageContext(this, request, response,null, true, 8192, true); 

So pageContext doesn't exist before the request is sent to the JSP.

Share:
12,910

Related videos on Youtube

Magnus
Author by

Magnus

Some things I've made https://mascii.org https://brahmsy.com http://bachsearch.com

Updated on September 15, 2022

Comments

  • Magnus
    Magnus over 1 year

    Does anyone know a way to get a JspContext reference from a servlet?

    I have a servlet that forwards to a Jsp and I'd like to set some PageContext variables from within the servlet so they're ready for consumption in the Jsp.

    • Magnus
      Magnus over 11 years
      Yeah I didn't think so either, but never underestimate the ingenuity of the SO community!
  • Magnus
    Magnus over 11 years
    Thanks for this answer. I know I can set objects in the request scope, but I wanted to set it in a jsp-specific scope specifically to avoid polluting the request scope on which the rest of the code relies. Part of the general OO philosophy of minimizing scope and visibility. Anyway, looks like the answer is "it can't be done".