向页面传参
- 把参数放到Model,Map或ModelMap中
@RequestMapping(value="/addUser")
public String addUser(Model model,Map map1,Map<String,Object> map2,ModelMap modelMap){
model.addAttribute("genders",Gender.values());
map1.put("cities",UserService.listCitys());
map2.put("skills",UserService.listSkills());
modelMap.addAttribute("user",new User());
return "/databind/addUser";
}
2 参数放到ModelAndView中
@RequestMapping(value="/modelAndView")
public ModelAndView modelAndView(){
ModelAndView mv=new ModelAndView();
mv.setViewName("/databind/parameters");
mv.addObject("title","modelAndView");
mv.addObject("cities",UserService.listCitys());
mv.addObject("skills",UserService.listSkills());
return mv;
}
3 参数放到request或session中
@RequestMapping(value="/sessionAttribute")
public String sessionAttribute(HttpServletRequest request){
request.setAttribute("title", "Hello World");
HttpSession session=request.getSession();
session.setAttribute("cities",UserService.listCitys());
session.setAttribute("skills",UserService.listSkills());
return "/databind/session";
}
获取页面参数
1 从request 中获取
@RequestMapping(value="/disPlayUser1")
public void disPlayUser1(Writer writer,HttpServletRequest request) throws IOException{
writer.write("username:"+request.getParameter("username")+"\n");
writer.write("gender:"+request.getParameter("gender")+"\n");
writer.write("birthday:"+request.getParameter("birthday")+"\n");
writer.write("skills:"+Arrays.asList(request.getParameterMap().get("skills"))+"\n");
writer.write("city:"+request.getParameter("city")+"\n");
writer.write("description:"+request.getParameter("description")+"\n");
}
2 通过参数传递 controller参数名和表单元素的name属性相同
<form action="disPlayUser2.mvc">
username:<input type="text" name="username">
@RequestMapping(value="/disPlayUser2")
public void disPlayUser2(Writer writer,String username,Gender gender,String birthday,
String[] skills,String city,String description) throws IOException{//不能用List<String> skills
writer.write("username:"+username+"\n");
writer.write("gender:"+gender+"\n");
writer.write("birthday:"+birthday+"\n");
writer.write("skills:"+Arrays.asList(skills)+"\n");
writer.write("city:"+city+"\n");
writer.write("description:"+description);
}
3 通过PO传递 如果使用springmvc标签库,设置表单的modelAttribute属性,path指定要绑定的属性名
<mvc:form modelAttribute="user" action="saveUser.mvc">
<mvc:label path="username">username:</mvc:label>
public void disPlayUser(Writer writer,User user) throws IOException{
writer.write(user.toString());
}