11

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;
}
vtor
  • 8,989
  • 7
  • 51
  • 67
cometta
  • 35,071
  • 77
  • 215
  • 324

4 Answers4

17

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;
}
MatBanik
  • 26,356
  • 39
  • 116
  • 178
  • Usually spring is configure with the view suffix, so you should not include it in the view name (html) – Bozho Dec 31 '10 at 17:43
  • Thanks! Didn't know we could turn it into a `HttpServlet#service()` method :-) One point to note is we can't use the `@RequestMapping` anymore when these two parameters are declared. – asgs Jan 03 '16 at 12:10
7
  1. Just pass it as argument: public String doSomething(HttpServletRequest request). You can pass both the request and response, or each of them individually.
  2. return the String "redirect:/viewname" (most often without the .jsp suffix)

For both questions, check the documentation, section "15.3.2.3 Supported handler method arguments and return types"

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
4

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.

vtor
  • 8,989
  • 7
  • 51
  • 67
  • 1
    @zygimantus No it does not work with response. There are some hacks to have it injected though (not recommended), check this post http://stackoverflow.com/questions/6984054/autowired-httpservletresponse – vtor Dec 05 '16 at 21:24
0

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";
    }
Sampath
  • 599
  • 5
  • 12