Accessing HttpServletRequest object in a normal Java class from Spring

后端 未结 2 1047
一生所求
一生所求 2020-12-15 20:02

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

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

相关标签:
2条回答
  • 2020-12-15 20:47

    @Context HttpServletRequest httpServletRequest =null;

    use this

    0 讨论(0)
  • 2020-12-15 20:53

    Use

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

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

    is it unstable to access it this way?

    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
    }
    
    0 讨论(0)
提交回复
热议问题