spring mvc 重定向,转发和传参

重定向:

(1)第一种情况:不需要传递参数。

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

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

 

(2)第二种情况:带参数

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

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

这样在toController这个方法中就可以通过获得参数的方式获得这个参数,再传递到页面。


不拼接url:

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

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

 

posted @ 2016-05-02 01:15  qiujiazhen  阅读(8226)  评论(0编辑  收藏  举报