问题
How do I get the request/response that I can setcookie? Additionally, at the end of this method, how can I can redirect to another page?
@RequestMapping(value = "/dosomething", method = RequestMethod.GET)
public RETURNREDIRECTOBJ dosomething() throws IOException {
....
return returnredirectpagejsp;
}
回答1:
How about this:
@RequestMapping(value = "/dosomething", method = RequestMethod.GET)
public ModelAndView dosomething(HttpServletRequest request, HttpServletResponse response) throws IOException {
// setup your Cookie here
response.setCookie(cookie)
ModelAndView mav = new ModelAndView();
mav.setViewName("redirect:/other-page");
return mav;
}
回答2:
- Just pass it as argument:
public String doSomething(HttpServletRequest request). You can pass both the request and response, or each of them individually. - return the
String"redirect:/viewname"(most often without the.jspsuffix)
For both questions, check the documentation, section "15.3.2.3 Supported handler method arguments and return types"
回答3:
You can also simply @Autowire. For example:
@Autowired
private HttpServletRequest request;
Though HttpServletRequest is request-scoped bean, it does not require your controller to be request scoped, as for HttpServletRequest Spring will generate a proxy HttpServletRequest which is aware how to get the actual instance of request.
回答4:
You could also use this way
@RequestMapping(value = "/url", method = RequestMethod.GET)
public String method(HttpServletRequest request, HttpServletResponse response){
Cookie newCookie = new Cookie("key", "value");
response.addCookie(newCookie);
return "redirect:/newurl";
}
来源:https://stackoverflow.com/questions/4564465/spring-controller-get-request-response