1. Overview
In this quick tutorial, we’ll discuss the difference between getRequestURI() and getPathInfo() in the HttpServletRequest class.
2. Difference Between getRequestURI() and getPathInfo()
The function getRequestURI() returns the complete requested URI. This includes the deployment folder and servlet-mapping string. It will also return all extra path information.
The function getPathInfo() only returns the path passed to the servlet. If there is no extra path information passed, this function will return null.
In other words, if we deploy our application in our web server’s root, and we request the servlet mapped to “/”, both getRequestURI() and getPathInfo() will return the same string. Otherwise, we’ll get different values.
3. Example Request
In order to get a better understanding of the HttpServletRequest methods, let’s say we have a servlet which can be accessed via this URL:
http://localhost:8080/deploy-folder/servlet-mapping
This request will hit the “servlet-mapping” servlet in a web application deployed inside “deploy-folder”. Therefore, if we call getRequestURI() and getPathInfo() for this request, they will return different strings.
Let’s create a simple doGet() servlet method:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
if ("getPathInfo".equals(request.getParameter("function")) {
writer.println(request.getPathInfo());
} else if ("getRequestURI".equals(request.getParameter("function")) {
writer.println(request.getRequestURI());
}
writer.flush();
}
Firstly, let’s take a look at the output of the servlet for getRequestURI requests fetched by curl command:
curl http://localhost:8080/deploy-folder/servlet-mapping/request-path?function=getRequestURI
/deploy-folder/servlet-mapping/request-path
Similarly, let’s take a look at the output of the servlet for getPathInfo:
curl http://localhost:8080/deploy-folder/servlet-mapping/request-path?function=getPathInfo
/request-path
4. Conclusion
In this article, we’ve explained the difference between getRequestURI() and getPathInfo() in HttpServletRequest. We also demonstrated it with an example servlet and request.
As always, the servlet implemented to test all these functions is available over on Github.