spring 获取 POJO 类中的 Servlet Request 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6300812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 04:32:25  来源:igfitidea点击:

Get the Servlet Request object in a POJO class

springjakarta-ee

提问by NRaf

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

我需要在从 Acegi 类调用的 POJO 中获取当前页面 URL(需要为我正在处理的应用程序添加一些自定义逻辑)并且需要检索 HttpServletRequest 以便我可以获取子域URL(逻辑所基于的)。

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?

知道我做错了什么或者我如何更好地去做这件事吗?

回答by sourcedelica

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

如果 bean 是请求范围的,您可以像您一样自动装配 HttpServletRequest。

@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 RequestContextListeneror RequestContextFilterin your web.xml.

如果您使用的是 Spring MVC,这就是您所需要的。如果你不使用Spring MVC的,那么你将需要注册一个RequestContextListenerRequestContextFilter两个web.xml