在Spring MVC中,可以通過(guò)ModelAndView
對(duì)象實(shí)現(xiàn)重定向。
使用ModelAndView
對(duì)象進(jìn)行重定向的步驟如下:
ModelAndView
對(duì)象,將重定向目標(biāo)URL作為構(gòu)造函數(shù)的參數(shù)。ModelAndView modelAndView = new ModelAndView("redirect:/redirectUrl");
addFlashAttribute
方法,將一些數(shù)據(jù)添加到重定向請(qǐng)求的Session中。modelAndView.addFlashAttribute("key", "value");
ModelAndView
對(duì)象。return modelAndView;
完整的示例代碼如下:
@Controller
public class MyController {
@RequestMapping("/redirect")
public ModelAndView redirect() {
ModelAndView modelAndView = new ModelAndView("redirect:/redirectUrl");
modelAndView.addFlashAttribute("key", "value");
return modelAndView;
}
@RequestMapping("/redirectUrl")
public ModelAndView redirectUrl(@ModelAttribute("key") String value) {
ModelAndView modelAndView = new ModelAndView("redirectPage");
modelAndView.addObject("value", value);
return modelAndView;
}
}
在上述示例中,redirect
方法將會(huì)重定向到redirectUrl
方法。redirectUrl
方法接收到重定向請(qǐng)求后,將會(huì)將之前添加到Session的數(shù)據(jù)取出,并傳遞給redirectPage
視圖。