Get the Servlet Request object in a POJO class

邮差的信 提交于 2020-01-09 12:43:31

问题


I need to get the current page URL in a POJO that is being called from an Acegi class (need to add some custom logic for the app I'm working on) and need to retrieve the HttpServletRequest so that I can get the subdomain of the URL (on which the logic is based).

I've tried to add:

@Autowired
private HttpServletRequest request;

...

public void setRequest(HttpServletRequest request) {
    this.request = request;
}

public HttpServletRequest getRequest() {
    return request;
}

However when I try to use the request object in my code, it is null.

Any idea what I am doing wrong or how I can better go about doing this?


回答1:


If the bean is request scoped you can autowire the HttpServletRequest like you are doing.

@Component
@Scope("request")
public class Foo {
    @Autowired private HttpServletRequest request;

    //
}

Otherwise you can get the current request as follows:

    ServletRequestAttributes sra = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    HttpServletRequest req = sra.getRequest();     

This uses thread-local under the covers.

If you are using Spring MVC that's all you need. If you are not using Spring MVC then you will need to register a RequestContextListener or RequestContextFilter in your web.xml.



来源:https://stackoverflow.com/questions/6300812/get-the-servlet-request-object-in-a-pojo-class

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