从 Spring 访问普通 Java 类中的 HttpServletRequest 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9767480/
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-08-16 07:25:10  来源:igfitidea点击:

Accessing HttpServletRequest object in a normal Java class from Spring

javaservletsspring-mvc

提问by mmm

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

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

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

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

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 have seen

我见过

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

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

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

采纳答案by skaffman

Use

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

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

我不确定你从哪里得到的RequestContextHolder.getRequestContext(),这是完全错误的。

is it unstable to access it this way?

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

No, it's stable enough, assuming you're always running the code as part of an HttpServletrequest 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.

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

If you mustuse 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
}

回答by user3465058

@Context HttpServletRequest httpServletRequest =null;

@Context HttpServletRequest httpServletRequest =null;

use this

用这个