Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use of request.getContextPath in a JSP

 
Ghazala Islam
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://www.mydomain.com:8080/myWebApp/index.html

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.
 
Ghazala Islam
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 65220
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic