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

查看:109
本文介绍了获取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;
}

但是当我尝试在我的代码中使用请求对象时,它为null 。

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

这使用了本地线程。

如果您正在使用Spring MVC,那就是您所需要的一切。如果您没有使用Spring MVC,则需要注册 RequestContextListener web.xml 中过滤/ RequestContextFilter.htmlrel =noreferrer> RequestContextFilter

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天全站免登陆