What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

a k picture a k · May 1, 2011 · Viewed 158.4k times · Source

I have a web app, where I have different navigation anchor tags such as Home, Profile and etc.

What I want:

When I press anchor tags like home or profile. I just want to ensure that current user gets its information in that Tags/JSP Page.

Sample Example that I am trying:

<a  href="${pageContext.request.contextPath}/JSPAddress.jsp">Profile</a>

Answer

no.good.at.coding picture no.good.at.coding · May 1, 2011

The pageContext is an implicit object available in JSPs. The EL documentation says

The context for the JSP page. Provides access to various objects including:
servletContext: ...
session: ...
request: ...
response: ...

Thus this expression will get the current HttpServletRequest object and get the context path for the current request and append /JSPAddress.jsp to it to create a link (that will work even if the context-path this resource is accessed at changes).

The primary purpose of this expression would be to keep your links 'relative' to the application context and insulate them from changes to the application path.


For example, if your JSP (named thisJSP.jsp) is accessed at http://myhost.com/myWebApp/thisJSP.jsp, thecontext path will be myWebApp. Thus, the link href generated will be /myWebApp/JSPAddress.jsp.

If someday, you decide to deploy the JSP on another server with the context-path of corpWebApp, the href generated for the link will automatically change to /corpWebApp/JSPAddress.jsp without any work on your part.