source: http://stackoverflow.com/questions/12236590/retrieving-the-servlet-context-path-from-a-spring-web-application
Q:
I would like to be able to dynamically retrieve the "servlet context path" (e.g.
Q:
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 aService 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 applicationand having it available for retrieval at all time by all my services?
A:
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());
}
}
See also this answer to a related question: stackoverflow.com/a/2066883/545127
댓글
댓글 쓰기