Partner – Payara – NPI (cat=Jakarta EE)
announcement - icon

Can Jakarta EE be used to develop microservices? The answer is a resounding ‘yes’!

>> Demystifying Microservices for Jakarta EE & Java EE Developers

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.