获取 POJO 类中的 Servlet Request 对象 [英] Get the Servlet Request object in a POJO class

查看:23
本文介绍了获取 POJO 类中的 Servlet Request 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我尝试添加:

@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?

推荐答案

如果 bean 是请求范围的,你可以像你正在做的那样自动装配 HttpServletRequest.

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.

如果您使用的是 Spring MVC,这就是您所需要的.如果你没有使用 Spring MVC 那么你需要注册一个 RequestContextListenerRequestContextFilter 在您的 web.xml 中.

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.

这篇关于获取 POJO 类中的 Servlet Request 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆