1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| package org.common.controller;
import java.util.HashMap; import java.util.Map;
import org.common.model.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;
@Controller @RequestMapping("/user") public class UserController { private Map<String,User> users = new HashMap<String,User>(); //创建一个users对象 public UserController() { users.put("ldh",new User("ldh","刘德华","123","123123")); users.put("zxy",new User("zxy","张学友","123","123123")); users.put("gfc",new User("gfc","郭富城","123","123123")); users.put("lm",new User("lm","黎明","123","123123")); } @RequestMapping(value="/users",method=RequestMethod.GET) public String list(Model model){ model.addAttribute("users", users); return "user/list"; } //链接到add页面时候是GET请求,会访问这段代码 @RequestMapping(value="/add",method=RequestMethod.GET) //把一个对象放到了@ModelAttribute中,Model的Key就是user public String add(@ModelAttribute("user") User user){ //开启modeDrive //model.addAttribute(new User()); return "user/add"; } //在具体添加用户的时候,是POST请求,就访问以下代码 @RequestMapping(value="/add",method=RequestMethod.POST) public String add(@Validated User user,BindingResult br){//一定要紧跟@Validated之后写验证结果类 if(br.hasErrors()){ //如果有错误,直接跳转到add视图 return "user/add"; } users.put(user.getUsername(),user); return "redirect:/user/users"; } // //链接到add页面时候是GET请求,会访问这段代码 // @RequestMapping(value="/add",method=RequestMethod.GET) // public String add(Model model){ // //开启modeDrive // model.addAttribute(new User()); // return "user/add"; // } // // //在具体添加用户的时候,是POST请求,就访问以下代码 // @RequestMapping(value="/add",method=RequestMethod.POST) // public String add(User user){ // users.put(user.getUsername(),user); // return "redirect:/user/users"; // } }
|