1:
@RequestMapping(value = "test/redirect")
public String testRedirect(Model model, String username){
Tdepartment td = new Tdepartment(2, "wwww", 3);
model.addAttribute("username",username);
model.addAttribute("tdepartment",td);
return "redirect:/hello/final/target";
}
2:
@RequestMapping(value = "final/target")
public String finalTarget(String username,Tdepartment tdepartment){
System.out.println(username);
System.out.println(tdepartment);
return null;
}
从1重定向到2,可以把数据放到model里面然后传到2,但是只能传String和些基本类型。
传集合list时,抛出nested exception is java.lang.IllegalArgumentException一个非法参数异常。
当然也可以通过直接在路径上拼接的方式return "redirect:/hello/final/target?username="www";,其实通过model来传递参数就是会 解析成这个样子的。当然对象也是传不过去的,如方法1中传不过去td对象,也就是说td在重定向的时候已经不存活了,所以在2中我们无法获取。
那么怎么重定向的时候传一个对象呢?我们可以使用session,在1中把对象放到session中,然后在方法2中把对象从session中取出来。代码如下:
1:
@RequestMapping(value = "test/redirect")
public String testRedirect(Model model, String username, HttpServletRequest request){
Tdepartment td = new Tdepartment(2, "wwww", 3);
model.addAttribute("username",username);
model.addAttribute("tdepartment",td);//对象传不过去
request.getSession().setAttribute("tdepartment",td);
return "redirect:/hello/final/target";
}
2:
@RequestMapping(value = "final/target")
public String finalTarget(String username,Tdepartment tdepartment,HttpServletRequest request){
System.out.println(username);
System.out.println(tdepartment);
System.out.println(request.getSession().getAttribute("tdepartment"));
return null;
}
当然SpringMVC也给我们提供了一中实现方式RedirectAttributes接口,该接口也是实现Model接口,通过addFlashAttribute();方法,把对象放进去,然后就可以把td对象传过去了,( redirectAttributes.addAttribute("user",new User(1,"wmin","www"));这个方法也是传不了对象的)实现的原理也是通过session实现,首先在方法1中把td对象存入session中,重定向的时候在把td对象拿出来,这样td对象就会一直存活了。
@RequestMapping(value = "test/redirectAttributes")
public String testRedirectAttributes(RedirectAttributes redirectAttributes){
redirectAttributes.addAttribute("user",new User(1,"wmin","www"));
Tdepartment td = new Tdepartment(1, "wwww", 2);
redirectAttributes.addFlashAttribute("tdepartment",td);
return "redirect:/hello/final/target";
}
SpringMVC就分享到这里,如有错误的地方,欢迎大家留言