Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 4535

Context Path vs. Servlet Path in Spring

$
0
0

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

When we update the servlet path, it also affects the context of the application. So, after these modifications, the application context path will become http://localhost:8080/baeldung/demo.

In other words, if a style sheet was being served as http://localhost:8080/demo/style.css, now will serve as http://localhost:8080/baeldung/demo/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.

       

Viewing all articles
Browse latest Browse all 4535

Trending Articles