DispatcherServlet plays a significant role in Spring applications and provides a single entry point for the application. Whereas the context path defines the URL that the end-user will access the application.
In this tutorial, we’re going to learn about the differences between context path and servlet path.
2. Context Path
Simply put, the context path is a name with which a web application is accessed. It is the root of the application. By default, Spring Boot serves the content on the root context path (“/”).
So, any Boot application with default configuration can be accessed as:
However, in some cases, we may wish to change the context of our application. There are multiple ways to configure the context path, and application.properties is one of them. This file resides under the src/main/resources folder.
Let’s configure it using the application.properties file:
As a result, the application main page will be:
When we deploy this application to an external server, this modification helps us to avoid accessibility issues.
3. Servlet Path
The servlet path represents the path of the main DispatcherServlet. The DispatcherServlet is an actual Servlet, and it inherits from HttpSerlvet base class. The default value is similar to the context path, i.e. (“/”):
In the earlier versions of Boot, the property was in the ServerProperties class and known as server.servlet-path=/.
From 2.1.x, this property is moved to the WebMvcProperties class and renamed as spring.mvc.servlet.path=/.
Let’s modify the servlet path:
Because a servlet belongs to a servlet context, changing the context path will affect the servlet path too. So, after modifications, the application servlet path will become http://localhost:8080/demo/baeldung.
In other words, if a style sheet was being served as http://localhost:8080/demo/style.css, now will serve as http://localhost:8080/demo/baeldung/style.css.
Usually, we don’t configure the DispatcherServlet by ourselves. But, if we really need to do it, we have to provide the path of our custom DispatcherServlet.
In this quick article, we looked at the semantics of context path and servlet path. We also saw what these terms represent and how they work together in a Spring application.