从Spring访问普通Java类中的HttpServletRequest对象 [英] Accessing HttpServletRequest object in a normal Java class from Spring

查看:896
本文介绍了从Spring访问普通Java类中的HttpServletRequest对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring MVC 3.06 Web应用程序中有一个普通的Java类。

I have a normal Java class in a Spring MVC 3.06 web application.

在这个类中,我想在方法中注入或获取 HttpServletRequest 对象。

In this class I would like to inject or get hold of the HttpServletRequest object in a method.

我知道我可以传递这个,但我想知道如何在不将其传递给方法的情况下获取请求。也许使用注释或类似的东西?

I know I can pass this around, but I was wondering how can I get hold of the request without passing it in to the method. Perhaps using annotations or similar?

此外,以这种方式获取请求的真实问题是什么,除了一些人认为它是丑陋的编码。我的意思是,以这种方式访问​​它是否不稳定?

Also, what are the "real" concerns with getting hold of the request this way, except some peoples opinions of it being ugly coding. I mean, is it unstable to access it this way?

最好不依赖于应用服务器的方式。

Preferably non application server dependent way.

I已见过

(HttpServletRequest) RequestContextHolder.getRequestContext().getExternalContext().getNativeRequest() 

但这似乎不适用于Spring MVC 3.06。 RequestContextHolder 没有方法 getRequestContext()

but this doesn't seem to work for Spring MVC 3.06 . RequestContextHolder doesn't have the method getRequestContext().

推荐答案

使用

((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

我不知道你在哪里 RequestContextHolder.getRequestContext(),这是完全错误的。

I'm not sure where you got RequestContextHolder.getRequestContext(), that's completely wrong.


以这种方式访问​​它是不稳定的?

is it unstable to access it this way?

不,它足够稳定,假设您始终将代码作为 HttpServlet 请求线程的一部分运行。主要问题是,它是丑陋的,它使您的代码难以测试。这是足够的理由不使用它。

No, it's stable enough, assuming you're always running the code as part of an HttpServlet request thread. The main issue is that yes, it's ugly, and it makes your code hard to test. That is reason enough not to use it.

如果必须使用它,那么将它与代码分离,例如

If you must use it, then decouple it from your code, e.g.

public void doSomething() {
    HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    doSomething(request);
}

void doSomething(HttpServletRequest request) {
   // put your business logic here, and test this method
}

这篇关于从Spring访问普通Java类中的HttpServletRequest对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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