Blog About Contact

Demystifying HttpServletRequest properties...

Published Fri, 12 Aug 2011 • 1 comments

I always find myself writing little test cases to figure out which methods to call on HttpServletRequest to get path / parameter information when doing low level Servlet and Filter programming.

The method naming and Javadoc is pretty poor for this part of the Java API and it's always confusing as to how to interrogate the request to figure out which bits of information you want from the request URL and parameters.

I thought I save myself (and you) the effort of doing this again, once and for all, by writing a quick post which summarises all the interesting "getters" on the HttpServletRequest:

Say I have a request going to a Java web application deployed at context path "WebApplication1" on my localhost sever, running on port 8080 -

URL = "http://localhost:8080/WebApplication1/test?q=123&r=456"

Method Example Return Value Description
getContextPath/WebApplication1Returns the deployed context path without the host/port, but including the preceding "/"
getQueryString q=123&r=456Returns query parameters as provided in the url, everything to the right of the "?"
getRequestURI /WebApplication1/testReturns the request path, without query parameters or host
getRequestURL http://localhost:8080/WebApplication1/testReturns the full request URL, without query parameters
getServletPath /testReturns the relative path within your web application, not including query parameters
getServerName localhostReturns the server hostname as per URL
getServerPort 8080Returns server port as per URL

About the Author

Richard Nichols is an Australian software engineer with a passion for making things.

Follow him on twitter or subscribe by RSS or email.

You might also enjoy reading -


Discuss / Comment

There are 1 comments.

Add a comment

  • {{e.error}}

Thanks for your comment!/

Required.
Valid email address required.
Required.
Posting message, please wait...