随笔 - 110  文章 - 1  评论 - 0  阅读 - 77445

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   骑着母猪去打猎  阅读(539)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示