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
| @Controller
@RequestMapping("/four")
public class FourController {
private static final Log logger = LogFactory.getLog(FourController.class);
private final FourUserService fourUserService;
@Autowired
public FourController(FourUserService fourUserService) {
this.fourUserService = fourUserService;
}
/**
* 第一次加载表单会触发这个方法
*/
@RequestMapping("/input")
public String inputUser(Model model) {
HashMap<String, String> hobbys = getMap();
// 虽然是第一次加载,但是也要在model添加一个领域模型的对象,否则表单标签无法找到modelAttribute属性指定的form backing object
model.addAttribute("user", new User());
model.addAttribute("hobbys", hobbys);
model.addAttribute("carrers", new String[]{"教师", "学生", "码农", "民工"});
model.addAttribute("houseRegister", new String[]{"北京", "上海", "广州", "深圳"});
return "userAdd";
}
/**
* 表单提交的时候会触发这个方法
*/
@RequestMapping("/save")
public String addUser(@ModelAttribute User user, Model model) {
// 进入业务层验证业务逻辑
if (fourUserService.addUser(user)) {
logger.info("成功");
// 重定向到本控制器里的list控制方法
return "redirect:list";
}
logger.info("失败");
// 验证失败的时候就到了这里,相当于重新加载,但是会带着已经填过的数据,用户就不用再次填写已经填写过的输入,注意这里没有在model.addAttribute()中new bean()。看不懂请对比上面的input方法
HashMap<String, String> hobbys = getMap();
model.addAttribute("hobbys", hobbys);
model.addAttribute("carrers", new String[]{"教师", "学生", "码农", "民工"});
model.addAttribute("houseRegister", new String[]{"北京", "上海", "广州", "深圳"});
return "userAdd";
}
@RequestMapping("/list")
public String listUsers(Model model) {
List<User> users = fourUserService.getUsers();
model.addAttribute("users", users);
return "userList";
}
private HashMap<String, String> getMap() {
HashMap<String, String> hobbys = new HashMap<>(5);
hobbys.put("篮球", "篮球");
hobbys.put("乒乓球", "乒乓球");
hobbys.put("电玩", "电玩");
hobbys.put("游泳", "游泳");
return hobbys;
}
}
|