Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving the servlet context path from a Spring web application

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?

like image 581
balteo Avatar asked Sep 02 '12 14:09

balteo


1 Answers

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());     } } 
like image 92
Andreas Berger Avatar answered Sep 30 '22 13:09

Andreas Berger