Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is a need of pageContext in JSP?

Tags:

java

jsp

el

When we can access all the implicit variables in JSP, why do we have pageContext ?

My assumption is the following: if we use EL expressions or JSTL, to access or set the attributes we need pageContext. Let me know whether I am right.

like image 941
Dead Programmer Avatar asked Sep 17 '10 12:09

Dead Programmer


People also ask

How can I get PageContext in JSP?

The pageContext object is used to represent the entire JSP page. This object is intended as a means to access information about the page while avoiding most of the implementation details. This object stores references to the request and response objects for each request.

How many scopes are in PageContext object?

pageContext getAttribute(String) is for page scope The one-arg version works just like all the others—it's for attributes bound TO the pageContext object. But the two-arg version can be used to get an attribute from ANY of the four scopes.


1 Answers

You need it to access non-implicit variables. Does it now make sense?


Update: Sometimes would just like to access the getter methods of HttpServletRequest and HttpSession directly. In standard JSP, both are only available by ${pageContext}. Here are some real world use examples:


Refreshing page when session times out:

<meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}"> 

Passing session ID to an Applet (so that it can communicate with servlet in the same session):

<param name="jsessionid" value="${pageContext.session.id}"> 

Displaying some message only on first request of a session:

<c:if test="${pageContext.session['new']}">Welcome!</c:if> 

note that new has special treatment because it's a reserved keyword in EL, at least, since EL 2.2


Displaying user IP:

Your IP is: ${pageContext.request.remoteAddr}

Making links domain-relative without hardcoding current context path:

<a href="${pageContext.request.contextPath}/login">login</a> 

Dynamically defining the <base> tag (with a bit help of JSTL functions taglib):

<base href="${fn:replace(pageContext.request.requestURL, pageContext.request.requestURI, pageContext.request.contextPath)}/"> 

Etcetera. Peek around in the aforelinked HttpServletRequest and HttpSession javadoc to learn about all those getter methods. Some of them may be useful in JSP/EL as well.

like image 152
BalusC Avatar answered Oct 11 '22 20:10

BalusC