Image of How to get the context path in a Spring Web application

ADVERTISEMENT

Introduction

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.

@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.

@Autowired
private ServletContext context;

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

context.getContextPath()

Summary

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

Next Steps

If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.