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



我希望能够动态地服务springbean检索我的spring-web应用程序的"servlet上下文路径"(例如http://localhost/myapphttp://www.mysite.com)。

原因是我想在发送给网站用户的电子邮件中使用这个值。

虽然从SpringMVC控制器中实现这一点非常容易,但从Servicebean中实现这并不明显。

有人能提出建议吗?

编辑:附加要求:

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

如果使用Servlet Container>=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());
    }
}

正如Andreas所建议的,您可以使用Servlet上下文。我这样使用它来获取我的组件中的属性:

    @Value("#{servletContext.contextPath}")
    private String servletContextPath;

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

String path = request.getRequestURL().toString();
myService.doSomethingIncludingEmail(..., path, ...);

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

如果它是UI流的一部分,那么你实际上可以在任何层的HttpServletRequest中注入,这是有效的,因为如果你在HttpServletRequest中注入,Spring实际上注入了一个代理,该代理委托给实际的HttpServlet请求(通过在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);
 }
}

使用Spring Boot,您可以在application.properties:中配置上下文路径

server.servlet.context-path=/api

然后,您可以从ServiceController获取路径,如下所示:

import org.springframework.beans.factory.annotation.Value;
@Value("${server.servlet.context-path}")
private String contextPath;

最新更新