SPRING MVC转发、重定向及传递参数方法

转发

常用两种方法

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";

在页面中直接调用msg,如index.jsp页面中以下代码

<c:out value='${msg }' />

 

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中,在跳转后马上移除对象。所以刷新页面后就没了

在页面中直接调用msg,如index.jsp页面中以下代码

<c:out value='${msg }' />

 

也可以直接接收HttpServletRequest,HttpServletResponse

@RequestMapping(value = "/saveUser", 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;  
}  

 

posted on 2022-03-30 09:32  骑着母猪去打猎  阅读(556)  评论(0)    收藏  举报