How to get the context path in a Spring Web application

In this tutorial, we discuss 2 ways for retrieving the context path in a Spring Web application.

1- HttpServletRequest

The typical way of getting the context path is through the HttpServletRequest class.

Simply you can add a HttpServletRequest parameter to your controller method and then get the context path using getContextPath() method.

Now that you get the context path, you can pass it to the services that need it.

2- ServletContext

If you want to get the context path from within a service or a component or anywhere inside your application and you don’t want to pass it as a parameter from your controller, then you can use ServletContext.

Simply add a class field of type ServletContext and annotate it with @Autowired.

Now inside your method, you can get the context path through:

0 0 votes
Article Rating

Hussein Terek

Owner of, I have a passion for software engineering and everything related to Java environment.

Inline Feedbacks
View all comments