Friday, October 16, 2009

Understanding Variables and Scope in JSPs













Understanding Variables and Scope in JSPs


Before discussing each of the tags in this library, it's necessary to review how variables and scope work in JSPs. First, remember that JSPs get converted into servlets and then compiled before they are executed. All of the HTML and code inside the JSP gets placed into the generated servlet's service( ) method. Because of this, any variables that get defined inside the JSP with a scriptlet, as shown here, are local to the service( ) method:


<%
String test = "test value";
%>

Similarly, any variables that are defined with a JSP declaration are local to the service( ) method:


<%! String test = "test value"; %>

Also, all of the implicit JSP objects, such as application, request, and session, are local to the resulting servlet's service( ) method.


JSPs and servlets also have the notion of "scope" for variables, because some variables need to persist longer than the lifespan of a page request and some variables need to be accessible outside of a servlet's service( ) method. There are four scopes that JSP variables can be placed in: application, page, request, and session. The following table explains each scope.
























Scope



Description



application



Variables placed in this scope persist for the life of an application.



page



Variables placed in this scope persist until the current JSP's service( ) method completes. Included JSPs cannot see page scope variables from the page including them. Also, this scope is exclusive to JSPs.



request



Variables placed in this scope persist until processing for the current request is completed. This scope differs from page scope in that multiple servlets may be executed during the lifespan of a request. Page scope variables persist only for the execution of one servlet.



session



Variables placed in this scope persist until the current user's session is invalidated or expires. This scope is valid only if the JSP or servlet in question is participating in a session.




Note that variables must be explicitly placed into a scope, as shown here:


<%
request.setAttribute("reqScopeVar", "test");
%>

This snippet uses JSP's implicit request object to place a variable into request scope. Similarly, the following snippet uses JSP's implicit session object to place a variable into session scope:


<%
session.setAttribute("sesScopeVar", "test");
%>

Of course, variables can also be put into each of the scopes by JSP tag library tags.














No comments:

Post a Comment