File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSP and the fly likes Use of request.getContextPath in a JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "Use of request.getContextPath in a JSP" Watch "Use of request.getContextPath in a JSP" New topic

Use of request.getContextPath in a JSP

Ghazala Islam
Ranch Hand

Joined: Nov 22, 2000
Posts: 73
I am little confused about the use of getContextPath method in the following code of a JSP :

<a href="<%=request.getContextPath()%>/servlet/FrontController?action=sayHello">Say Hello</a>

<a href="<%=request.getContextPath()%>/servlet/FrontController?action=sayGoodbye">Say Goodbye</a>

<a href="<%=request.getContextPath()%>/servlet/FrontController?action=displayDate">Display Date</a>

The API for getContextPath()says "it returns the context path of requested URI " ,so what does it mean by �context path� of requested URI.
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

J2EE (now called Java EE) application servers can host more than one "webapp".
The portion of the URI just after the port (shown in bold) is known as the contextPath for a webapp.

In this case 'index.html' is in root directory of the webapp called myWebApp.

In those links you've posted, the developer (rightly) built the relative links by reading the contextPath from the request object. This allows for the renaming of the webapp without the need to alter every link in the app.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Ghazala Islam
Ranch Hand

Joined: Nov 22, 2000
Posts: 73
so you mean the context path in uri is used only when there is a possibility of change of webapp name,otherwise the code could've been :

a href ="/servlet/FrontController?action=displayDate">Display Date</a>
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63548

No. The point is that for resources referenced fomr the client such as images, style sheets and script files. the context path is required. Otherwise, the server wouldn't know which web app was being referenced.

If you hard-code the context path, you'd need to fix all these references up if it were to change.

[Asking smart questions] [About Bear] [Books by Bear]
jQuery in Action, 3rd edition
subject: Use of request.getContextPath in a JSP
It's not a secret anymore!