JSP URI/URL - How to get the request URI, URL, and Context from a JSP

JSP URI/URL FAQ: How do I get a URI or URL from a JSP (the request URI or request URL)?

I was just working with a JSP, and trying to remember how to get information that can be very helpful inside of a JSP, specifically how to determine the Context, URI, and URL from within a JSP.

To that end, here's the Java source code for a JSP I wrote that will display the Context, URI, and URL for this JSP when it is accessed from a browser:

<h2>JSP URI, URL, Context</h2>

Request Context Path: <%= request.getContextPath() %>
Request URI:          <%= request.getRequestURI() %>
Request URL:          <%= request.getRequestURL() %>

When I save this in a file named uriTest.jsp, place it in a context named test that is already running on a Tomcat server on my local computer, and then hit the URL for this JSP (http://localhost:8080/test/uriTest.jsp), I see the following output:

JSP URI, URL, Context

Request Context Path: /test
Request URI:          /test/uriTest.jsp
Request URL:          http://localhost:8080/test/uriTest.jsp

Information like this can be very helpful when doing a variety of things inside a JSP. For instance, in looking at the blog here at devdaily.com/blog, I want to add some social bookmark links here, and when doing that, I can use the =request.getRequestURI() or request.getRequestURL()= methods to get the URL information that I need to send to Digg, StumbleUpon, and others.

While I mentioned that I ran this test from within Tomcat, you'll use these same Java/JSP methods from within any servlet container, including Glassfish, JBoss, WebLogic, or WebSphere.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.