SpringMVC中modelandview重定向怎么實(shí)現(xiàn)

小億
294
2023-10-09 23:34:25

在Spring MVC中,可以通過(guò)ModelAndView對(duì)象實(shí)現(xiàn)重定向。

使用ModelAndView對(duì)象進(jìn)行重定向的步驟如下:

  1. 創(chuàng)建一個(gè)ModelAndView對(duì)象,將重定向目標(biāo)URL作為構(gòu)造函數(shù)的參數(shù)。
ModelAndView modelAndView = new ModelAndView("redirect:/redirectUrl");
  1. 可以使用addFlashAttribute方法,將一些數(shù)據(jù)添加到重定向請(qǐng)求的Session中。
modelAndView.addFlashAttribute("key", "value");
  1. 返回該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視圖。

0