springmvc重定向传递参数
@Controller
@RequestMapping("/personalData")
public class PersonalDataController {
//第一种,在重定向地址后带参数传递
@RequestMapping("/test1")
public String test1(String userId){
return "redirect:mytest?userId="+userId;
}
@RequestMapping("/mytest")
public String mytest(String userId){
System.out.println("------------"+userId+"-----------");
return view + "test";
}
//第二种,将参数放到RedirectAttributes里面,用@ModelAttribute注解获取参数,这里可接收字符串或集合
@RequestMapping("/test3")
public String test3(String userId, RedirectAttributes model){
User list1 = new Person("1","男","张三");
User list2 = new Person("1","男","李四");
List<User> list = new ArrayList<User>();
list.add(list1);
list.add(list2);
model.addFlashAttribute("userId",userId);
model.addFlashAttribute("list",list);
return "redirect:mytest";
}
@RequestMapping("/mytest")
public String mytest(@ModelAttribute("userId") String userId,@ModelAttribute("list") List<User> list){
System.out.println("------------"+userId+"-----------");
System.out.println("------------"+list.size()+"-----------");
return view + "test";
}
}
注意:这里如果传递的参数乱码,需要通过URLEncoder.encode("中文字符","UTF-8")编码,因为在request.getParameter("name")之前会做一次解码。