Spring MVC - Accessing HttpRequest from controller
Spring - accessing HttpRequest from controller
If you want to handle request and session attributes yourself rather then leave it to spring @SessionAttributes, e.g. for login of cookies or any other header parameters.
Spring MVC will give you the HttpRequest if you just add it to your controller method signature:
Simply adding the HttpServletRequest and HttpServletResponse objects to the signature makes Spring MVC to pass those objects to your controller method. You can pass the HttpSession object too.
Here is the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods: https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-methods/arguments.html
/**
* Generate a PDF report...
*/
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
@PathVariable("objectId") Long objectId,
HttpServletRequest request,
HttpServletResponse response) {
// ...
// Here you can use the request and response objects like:
// response.setContentType("application/pdf");
// response.getOutputStream().write(...);
}
Do not use this
@Autowired
private HttpServletRequest context;
Sample implementation: https://github.com/explorer436/programming-playground/tree/main/java-playground/spring-http-demo