SPRING MVC跳轉及傳遞引數方法
阿新 • • 發佈:2022-03-30
跳轉
常用兩種方法
1 使用ModelAndView
@RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET) public ModelAndView index(ModelAndView mv, Object obj) {
mv.addObject("obj", obj);
mv.setViewName("/index");
return mv;
}
2 直接返回String
@RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET)public String index(Model model, Object obj) { model.addAttribute("obj", obj); return "/index"; }
重定向
1 使用ModelAndView
return new ModelAndView("redirect:/index");
2 直接返回String
return "redirect:/index";
重定向傳參
1 直接拼接到url後面,頁面或controller直接取這個msg引數,但這種方法相當於位址列傳參,有可能對中文解碼不正確出現亂碼
return new ModelAndView("/index?msg=xxxxx");
return "redirect:/index?msg=xxxx";
@RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET) public ModelAndView index(ModelAndView mv, RedirectAttributes redirectAttributes, Object obj) { redirectAttributes.addAttribute("obj", obj); mv.setViewName("redirect:/index"); returnmv; }
@RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET) public String index(RedirectAttributes redirectAttributes, Object obj) { redirectAttributes.addAttribute("obj", obj); return "redirect:/index"; }
2 不拼接url引數,使用RedirectAttributes進行引數的存取
@RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET) public ModelAndView index(ModelAndView mv, RedirectAttributes redirectAttributes, Object obj) { redirectAttributes.addFlashAttribute("obj", obj); mv.setViewName("redirect:/index"); return mv; }
@RequestMapping(value = {"", "/", "/index"}, method = RequestMethod.GET) public String index(RedirectAttributes redirectAttributes, Object obj) { redirectAttributes.addFlashAttribute("obj", obj); return "redirect:/index"; }
取引數obj的時候,如果是頁面,可以直接表示式讀取。
但此值只能使用一次,重新整理頁面就沒了。原理是把這個值放到session中,在跳轉後馬上移除物件。所以重新整理頁面後就沒了
也可以直接接收HttpServletRequest,HttpServletResponse
@RequestMapping(value = "/index", method = RequestMethod.GET) public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response, UserModel user) throws Exception { ModelAndView mv = new ModelAndView("/user/save/result");//預設為forward模式 // ModelAndView mv = new ModelAndView("redirect:/user/save/result");//redirect模式 mv.addObject("message","儲存使用者成功!"); return mv; }