Controller至jsp中页面传值方法的记录

转载自:https://www.cnblogs.com/jpfss/p/8651303.html

springMVC controller间跳转 重定向 传递参数的方法

spring MVC框架controller间跳转,需重定向。有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示。
常用的方法:
(1)从一个controller中的方法跳转到另一个controller中的方法不需要传递参数
方式一:使用ModelAndView
return new ModelAndView(“redirect:/toList”);
这样可以重定向到另一个controller的toList这个方法
方式二:返回String
return “redirect:/ toList “;
这是不带参数的重定向。
( 2)第二种情况,需要携带参数时参数可以拼接url
方式一:自己手动拼接url
new ModelAndView(“redirect:/toList?param1=”+value1+”&param2=”+value2);
这样有个弊端,就是传中文可能会有乱码问题。
方式二:用RedirectAttributes,这个是发现的一个比较好用的一个类 , SpringMVC 自己的类
这里用它的addAttribute方法,这个实际上重定向过去以后你看url,是它自动给你拼了你的url。
使用方法:
public String save(RedirectAttributes attr)
attr.addAttribute(“param”, value);
return “redirect:/namespace/toController”;
这样在toController这个方法中就可以通过获得参数的方式获得这个参数,再传递到页面。过去的url还是和方式一
一样的。
获得参数的方式:
request.getParameter(“productActivityId”);
(3)带参数不拼接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”;
}
}
addFlashAttribute() springMVC3中 该方法将信息放到session中,在页面直接用el表达式就可以获得.session在跳到页面后
马上移除对象。所以你刷新一下后这个值就会丢掉。
总结
本质还是两次跳转,spring进行了封装;

猜你喜欢

转载自www.cnblogs.com/jndx-ShawnXie/p/11565930.html