Is there a way to get HttpServletRequest from the controller of spring mvc without adding a parameter to the method?

Asked 1 years ago, Updated 1 years ago, 64 views

I understand that to receive HttpServletRequest from the controller of spring mvc, you can add the parameter of the function as shown below.

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Map<String, Object> model) throws IOException {
        ...
    }

->

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Map<String, Object> model) throws IOException {
        request.doSomething(); 
    }

By the way, is there a way to just take out and write a request within the controller function without adding a parameter like this? Spring uses ThreadLocal a lot, but I think you saved the request somewhere, but I can't find it.

java spring springmvc

2022-09-22 22:02

1 Answers

The first method is as follows (Spring 2.0 or higher)

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

Example

@RequestMapping(value = "/", method = RequestMethod.GET)
 public String index() throws IOException {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
        .getRequestAttributes()).getRequest();
    // // do something
    ...
}

The second way is to declare and wire to a member of the class as follows:

@Autowired(required=true)
private HttpServletRequest request;


2022-09-22 22:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.