spring mvc 重定向,转发和传参

重定向:数据库

(1)第一种状况:不须要传递参数。session

方式一:使用ModelAndView
return new ModelAndView("redirect:/toList");
这样能够重定向到toList这个方法app

方式二:返回String
return "redirect:/ toList "; jsp

 

(2)第二种状况:带参数url

拼接url,用RedirectAttributes,这里用它的addAttribute方法,这个实际上重定向过去之后你看url
,是它自动给你拼了你的url。
使用方法:spa

attr.addAttribute("param", value);
return "redirect:/namespace/toController";code

这样在toController这个方法中就能够经过得到参数的方式得到这个参数,再传递到页面。orm


不拼接url:get

@RequestMapping("/save")
public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr)
throws Exception {io

String code = service.save(form);
if(code.equals("000")){
attr.addFlashAttribute("name", form.getName());
attr.addFlashAttribute("success", "添加成功!");
return "redirect:/index";
}else{
attr.addAttribute("projectName", form.getProjectName());
attr.addAttribute("enviroment", form.getEnviroment());
attr.addFlashAttribute("msg", "添加出错!");
return "redirect:/maintenance/toAddConfigCenter";
}
}

注意:1.使用RedirectAttributes的addAttribute方法传递参数会跟随在URL后面,如上代码即为
http:/index.action?a=a
2.使用addFlashAttribute不会跟随在URL后面,会把该参数值暂时保存于session,
待重定向url获取该参数后从session中移除,这里的redirect必须是方法映射路径,jsp无效。你会
发现redirect后的jsp页面中b只会出现一次,刷新后b不再会出现了,这验证了上面说的,b被访问
后就会从session中移除。对于重复提交能够使用此来完成.

另外,若是使用了RedirectAttributes做为参数,可是没有进行redirect呢?这种状况下不会
将RedirectAttributes参数传递过去,默认传forward对应的model,官方的建议是:

p:ignoreDefaultModelOnRedirect="true" />

设置下RequestMappingHandlerAdapter 的ignoreDefaultModelOnRedirect属性,这样能够提升效率
,避免没必要要的检索。


当保存POJO到数据库后,要返回成功页面,若是这个时候要带点信息,则要这样:

@RequestMapping(value = "/user/save", method = RequestMethod.POST)

public ModelAndView saveUser(UserModel user, RedirectAttributes redirectAttributes)
throws Exception {

redirectAttributes.addFlashAttribute("message", "保存用户成功!");//使用
addFlashAttribute,参数不会出如今url地址栏中

return "redirect:/user/save/result";

}

 

转发:

返回ModelAndView :
@RequestMapping(value="/test",method=RequestMethod.GET)
public ModelAndView testForward(ModelAndView model){

model.setViewName("forward:index.jsp");
return model;
}

如上代码,若是返回modelAndView 则能够如红色标注,添加forward便可,若想重定向,可把
forward替换成redirect即可达到目的。

返回String:

@RequestMapping(value="/forward",method=RequestMethod.GET)
public String testForward(){

return "forward:/index.action"; }

相关文章
相关标签/搜索