Search code examples
jsppagecontext

Page scope in jsp


I understand that page scope is the default scope in a jsp (least privileged as compared to request/session/application scope) and objects can be accessed only within the same jsp page.

I want to know if there is any possibility that two users accessing the same jsp page would share the object value that's been set at page scope? I highly feel that answer is No, but still want to confirm once.

In other terms does PageContext get shared between two users? If I set an object to page scope using pageContext.setAttribute(....), will this object be shared between two different users?


Solution

  • You can get a better understanding of how page scope works, by looking at how JSP page implementation classes use the PageContext object that represents said scope.

    In the javadoc for package javax.servlet.jsp there is an example of how this is done. The interesting part is:

    public void _jspService(HttpServletRequest request,
                            HttpServletResponse response)
                            throws IOException, ServletException {
    
        JspFactory  factory     = JspFactory.getDefaultFactory();
        PageContext pageContext = factory.getPageContext( ... )
    
        ...
    }
    

    As you can see, when your servlet forwards its request and response objects to a JSP, the _jspService method of its page implementation class is invoked, taking them as arguments. Right after, the method obtains a PageContext object and stores it as a local variable of the method.

    Local variables are thread memory (not shared), and thus, there is no way for any other thread serving a request from another user (and not even from the same user) to get access to that variable. Once _jspService returns, the variable simply ceases to exist. If another thread concurrently calls _jspService(), the factory gives it a different PageContext instance.

    This leads to the question of whether the PageContext object obtained from the factory is always a new instance or one being reused. This is implementation dependent, as explained in the answers to this question. In the latter case, the container should ensure that it never hands the same instance to two different threads at the same time (otherwise concurrency problems would arise).

    Notice that, before returning, _jspService() ensures that the PageContext object is "cleansed" of any state by calling releasePageContext() (see the finally block in the javadoc example). This in turn calls release() on the PageContext, with the effect of "releasing all internal references, and preparing the PageContext for potential reuse". So, when pooled instances are used, each thread always gets a "clean" one.