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.



thank you