Course – LS – All

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

>> CHECK OUT THE COURSE

1. Introduction

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:

http://localhost:8080/

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:

server.servlet.context-path=/demo

As a result, the application main page will be:

http://localhost:8080/demo

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. (“/”):

spring.mvc.servlet.path=/

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:

spring.mvc.servlet.path=/baeldung

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.

4. Conclusion

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.

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)
4 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!