Demystifying HttpServletRequest properties...
Published Thu, 11 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||/WebApplication1||Returns the deployed context path without the host/port, but including the preceding "/"|
|getQueryString||q=123&r=456||Returns query parameters as provided in the url, everything to the right of the "?"|
|getRequestURI||/WebApplication1/test||Returns the request path, without query parameters or host|
|getRequestURL||http://localhost:8080/WebApplication1/test||Returns the full request URL, without query parameters|
|getServletPath||/test||Returns the relative path within your web application, not including query parameters|
|getServerName||localhost||Returns the server hostname as per URL|
|getServerPort||8080||Returns server port as per URL|
About the Author
Richard Nichols is an Australian software engineer with a passion for making things.
You might also enjoy reading -
- Detecting Which Browser In Java Servlet/Filter
- LessCSS available in Java and Wicket - less.js
- Automatic release packaging w/ version numbers for Netbeans Java Projects...
- Simple Guide To Sub-reports in JasperReports / iReport
- Adding a Dynamic Watermark to an Image - Java Web Application