Spring controller get request/response

岁酱吖の 提交于 2020-02-03 04:04:06

问题


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:


  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"




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!