从Spring Web应用程序检索servlet上下文路径

bal*_*teo 32 spring servlets contextpath

我希望能够从Service spring bean 动态检索我的spring Web应用程序的" servlet上下文路径 "(例如http://localhost/myapphttp://www.mysite.com).

这样做的原因是我想在将要发送给网站用户的电子邮件中使用此值.

虽然从Spring MVC控制器执行此操作非常容易,但从Service bean执行此操作并不是那么明显.

任何人都可以建议吗?

编辑:附加要求:

我想知道是否有一种方法可以在启动应用程序时检索上下文路径,并且可以通过我的所有服务随时检索它?

And*_*ger 40

如果使用ServletContainer> = 2.5,则可以使用以下代码获取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());
    }
}
Run Code Online (Sandbox Code Playgroud)


stu*_*n3k 23

正如Andreas建议的那样,您可以使用ServletContext.我像这样使用它来获取我的组件中的属性:

    @Value("#{servletContext.contextPath}")
    private String servletContextPath;
Run Code Online (Sandbox Code Playgroud)


Ric*_*win 6

我会避免从服务层创建对Web图层的依赖.让您的控制器使用解析路径request.getRequestURL()并将其直接传递给服务:

String path = request.getRequestURL().toString();
myService.doSomethingIncludingEmail(..., path, ...);
Run Code Online (Sandbox Code Playgroud)


Bij*_*men 2

如果服务是由控制器触发的,我假设您可以使用 HttpSerlvetRequest 从控制器检索路径并将完整路径传递给服务。

如果它是 UI 流的一部分,您实际上可以HttpServletRequest在任何层中注入,它会起作用,因为如果您注入HttpServletRequest,Spring 实际上会注入一个代理,该代理委托给实际的 HttpServletRequest (通过在 中保留引用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);
 }
}
Run Code Online (Sandbox Code Playgroud)