Retrieving the servlet context path from a Spring web application

balteo picture balteo · Sep 2, 2012 · Viewed 81.9k times · Source

I would like to be able to dynamically retrieve the "servlet context path" (e.g. http://localhost/myapp or http://www.mysite.com) for my spring web application from a Service spring bean.

The reason for this is that I want to use this value in email that are going to be sent to users of the website.

While it would be pretty easy to do this from a Spring MVC controller, it is not so obvious to do this from a Service bean.

Can anyone please advise?

EDIT: Additional requirement:

I was wondering if there wasn't a way of retrieving the context path upon startup of the application and having it available for retrieval at all time by all my services?

Answer

Andreas Berger picture Andreas Berger · Feb 26, 2013

If you use a ServletContainer >= 2.5 you can use the following code to get the ContextPath:

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component

@Component
public class SpringBean {

    @Autowired
    private ServletContext servletContext;

    @PostConstruct
    public void showIt() {
        System.out.println(servletContext.getContextPath());
    }
}