Retrieving the servlet context path from a Spring web application

前提是你 提交于 2019-11-30 04:21:21

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());
    }
}

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;

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, ...);

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);
 }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!