Request context
Each http request is executed in its own thread. The data associated with the request is called request context.
Controller methods can use some request data as parameters with annotations, such as @RequestParam or with a special type, such as HttpSession. All request data can be accessed through the parameter with the type HttpServletRequest.
@Controller
@RequestMapping("/test")
class MyController {
@GetMapping("/doExample")
fun doExmaple(@RequestParam param: String, session: HttpSession) =
ModelAndView("mytemplate").apply {...}
@GetMapping("/doExample2")
fun doExmaple2(request: HttpServletRequest) =
ModelAndView("mytemplate").apply {...}
}
Other classes can get current request context from the RequestContextHolder object.
fun getCurrentHttpRequest(): HttpServletRequest? =
RequestContextHolder.getRequestAttributes()
?.takeIf { it is ServletRequestAttributes }
?.run {
this as ServletRequestAttributes
this.request }
public static HttpServletRequest getCurrentHttpRequest(){
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes instanceof ServletRequestAttributes) {
HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
return request;
}
return null;
}