转自:
Spring MVC中如何使用forward进行请求转发呢?
下文讲述Spring MVC进行请求转发的2种方式简介说明,如下所示:
Spring MVC种forward请求是一种服务器端请求方式,它无需通过客户端,可以提高系统的转发速度,
同时转发的时候,会借助HttpServletRequest转发请求信息,他们转发的是同一个request对象
例:
@RequestMapping(value="/testredirect",method = { RequestMethod.POST, RequestMethod.GET }) public String testredirect(HttpServletResponse response){ return "forward:/index"; }
@RequestMapping(value="/testredirect",method = { RequestMethod.POST, RequestMethod.GET }) public String testredirect(HttpServletRequest request){ request.setAttribute("username", "51gjie"); //把username参数传递到request中 return "forward:/user/index"; }
@RequestMapping(value="/restredirect",method = { RequestMethod.POST, RequestMethod.GET }) public ModelAndView restredirect(String userName){ ModelAndView model = new ModelAndView("forward:/main/index");//默认forward,可以不用写 return model; }
@RequestMapping(value="/toredirect",method = { RequestMethod.POST, RequestMethod.GET }) public ModelAndView toredirect(String userName){ ModelAndView model = new ModelAndView("/user/userinfo"); model.addObject("userName", userName); //把userName参数带入到controller的RedirectAttributes return model; }