问题
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?
回答1:
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());
}
}
回答2:
As Andreas suggested, you can use the ServletContext. I use it like this to get the property in my components:
@Value("#{servletContext.contextPath}")
private String servletContextPath;
回答3:
I would avoid creating a dependency on the web layer from your service layer. Get your controller to resolve the path using request.getRequestURL()
and pass this directly to the service:
String path = request.getRequestURL().toString();
myService.doSomethingIncludingEmail(..., path, ...);
回答4:
If the service is triggered by a controller, which I am assuming it is you can retrieve the path using HttpSerlvetRequest from the controller and pass the full path to the service.
If it is part of the UI flow, you can actually inject in HttpServletRequest
in any layer, it works because if you inject in HttpServletRequest
, Spring actually injects a proxy which delegates to the actual HttpServletRequest (by keeping a reference in a ThreadLocal
).
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
public class AServiceImpl implements AService{
@Autowired private HttpServletRequest httpServletRequest;
public String getAttribute(String name) {
return (String)this.httpServletRequest.getAttribute(name);
}
}
来源:https://stackoverflow.com/questions/12236590/retrieving-the-servlet-context-path-from-a-spring-web-application