Codebox Software

URL Parsing from Java Servlets


This page is intended to provide a simple guide for Java Servlet developers, who need to extract parts of request URLs using the methods of the HttpServletRequest class.

The methods provided by the API can be a little confusing to use - the names don't always make it clear what they are supposed return, and when there is no value available some of them return null while others pass back an empty string. The values returned also change depending on how the url is mapped to the servlet via the <url-pattern> elements in the web.xml deployment descriptor.

The following examples cover most of the common use-cases. Note that the value returned by getRequestURI() depends on exactly how the resource was specified in the HTTP request, the most likely value is shown in the examples but you may get something different under certain circumstances.

Example 1


Here the web application is deployed to the root context (so it's probably the only application running on this server), and is accessed using http on port 80.

getScheme() http
getServerName() example.com
getServerPort() 80
getContextPath() empty string
getServletPath() /showLogin
getPathInfo() null
getQueryString() null
getRequestURI() /showLogin

Example 2

URL: http://testserver:8080/MyApp/actions/logout

This example is more complicated, the application is running in the context 'MyApp' (this was the name given to the application when it was deployed, it may be running along side other applications on the server), and the server uses a non-standard port (8080). The web.xml deployment descriptor maps any requests that have '/actions/' after the context name to this servlet:

getScheme() httphttp://testserver:8080/MyApp/actions/logout
getServerName() testserverhttp://testserver:8080/MyApp/actions/logout
getServerPort() 8080http://testserver:8080/MyApp/actions/logout
getContextPath() /MyApphttp://testserver:8080/MyApp/actions/logout
getServletPath() /actionshttp://testserver:8080/MyApp/actions/logout
getPathInfo() /logouthttp://testserver:8080/MyApp/actions/logout
getQueryString() nullhttp://testserver:8080/MyApp/actions/logout
getRequestURI() /MyApp/actions/logouthttp://testserver:8080/MyApp/actions/logout

Example 3


In this example, the application is running in the context 'TestApp', and the request includes some parameters. The web.xml deployment descriptor maps any requests that end '.action' to this servlet:

getScheme() httphttp://
getServerPort() 80http://
getContextPath() /TestApphttp://
getServletPath() /actions/login.actionhttp://
getPathInfo() nullhttp://
getQueryString() user=rob&pass=kittenshttp://
getRequestURI() /TestApp/actions/login.actionhttp://