How do I get a HttpServletRequest in my spring beans?

前端 未结 6 1185
时光取名叫无心
时光取名叫无心 2020-12-01 01:48

I\'m developing an app with a Flex-based front end and a Spring/Hibernate back-end.

To get Facebook integration working in the way I\'ve got it currently, I need to

相关标签:
6条回答
  • 2020-12-01 02:24

    If FlexContext is not available:

    Solution 1: inside method (>= Spring 2.0 required)

    HttpServletRequest request = 
            ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes())
                    .getRequest();
    

    Solution 2: inside bean (supported by >= 2.5, Spring 3.0 for singelton beans required!)

    @Autowired
    private HttpServletRequest request;
    
    0 讨论(0)
  • 2020-12-01 02:38

    This is kind of Flex/BlazeDS specific, but here's the solution I've come up with. Sorry if answering my own question is a faux pas.

        HttpServletRequest request = flex.messaging.FlexContext.getHttpRequest();
    
        Cookie[] cookies = request.getCookies();
    
        for (Cookie c:cookies)
        {
            log.debug(String.format("Cookie: %s, %s, domain: %s",c.getName(), c.getValue(),c.getDomain()));
        }
    

    It works, I get the cookies. My problem was looking to Spring - BlazeDS had it. Spring probably does too, but I still don't know how to get to it.

    0 讨论(0)
  • 2020-12-01 02:42

    @eeezyy's answer didn't work for me, although I'm using Spring Boot (2.0.4) and it may differ, but a variation here in 2018 works thus:

    @Autowired
    private HttpServletRequest request;
    
    0 讨论(0)
  • 2020-12-01 02:42

    this should do it

    ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getRequestURI();
    
    0 讨论(0)
  • 2020-12-01 02:46

    Better way is to autowire with a constructor:

    private final HttpServletRequest httpServletRequest;
    
    public ClassConstructor(HttpServletRequest httpServletRequest){
          this.httpServletRequest = httpServletRequest;
    }
    
    0 讨论(0)
  • 2020-12-01 02:47

    The @Context annotation (see answers in this question :What does context annotation do in Spring?) will cause it to be injected for you.

    I had to use

    @Context
    private HttpServletRequest request;
    
    0 讨论(0)
提交回复
热议问题