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
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;
© 2025 OneMinuteCode. All rights reserved.