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.
1 2 3 4 5 | @RequestMapping(value = "/", method = RequestMethod.GET) public String home(HttpServletRequest request) throws IOException { System.out.println(request.getContextPath()); return "home"; } |
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.
1 2 | @Autowired private ServletContext context; |
Now inside your method, you can get the context path through:
1 | context.getContextPath() |