40

我希望能够从Service spring bean为我的 spring web 应用程序动态检索“ servlet 上下文路径”(例如http://localhost/myapp或) 。http://www.mysite.com

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

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

有人可以请教吗?

编辑:附加要求:

我想知道是否没有办法在应用程序启动时检索上下文路径并让我的所有服务始终可以检索它?

4

5 回答 5

59

如果您使用 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());
    }
}
于 2013-02-26T07:57:13.380 回答
29

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

    @Value("#{servletContext.contextPath}")
    private String servletContextPath;
于 2015-12-14T09:13:09.453 回答
6

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

String path = request.getRequestURL().toString();
myService.doSomethingIncludingEmail(..., path, ...);
于 2012-09-02T19:01:52.557 回答
2

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

如果它是 UI 流的一部分,您实际上可以HttpServletRequest在任何层中注入,它可以工作,因为如果您注入HttpServletRequest,Spring 实际上会注入一个代理,该代理委托给实际的 HttpServletRequest(通过在 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);
 }
}
于 2012-09-02T15:06:09.933 回答
1

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

server.servlet.context-path=/api

然后,您可以从 aServiceController像这样获取路径:

import org.springframework.beans.factory.annotation.Value;

@Value("${server.servlet.context-path}")
private String contextPath;
于 2021-01-25T13:24:03.563 回答