添加bean-validator.jar包
修改实体类User.java,添加默认构造器以及数据验证信息
package com.test.model; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; public class User { private String username; private String nickname; private String password; private String email; public User() { super(); } public User(String username, String nickname, String password, String email) { super(); this.username = username; this.nickname = nickname; this.password = password; this.email = email; } @NotEmpty(message="邮箱不能为空!") @Email(message="邮箱格式不正确!") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } @NotEmpty(message="密码不能为空!") @Size(min = 6, max = 10, message = "密码的长度必须在5到10位!") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @NotEmpty(message="用户名不能为空!") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
?
在Action控制器UserController.java中添加方法:
/** * 添加用户前 * * @param model * @return */ @RequestMapping(value = "/addUserPro", method = RequestMethod.GET) public String addUserPro(Model model) { // 如果不添加下面这一句的话,sf:form标签中的modelAttribute="user"会在request中找user实例,没有的话会报错 model.addAttribute(new User()); return "user/addUser"; } /** * 添加用户 * * @param user * @return */ @RequestMapping(value = "/addUser", method = RequestMethod.POST) // 这里的参数user要和页面上modelAttribute属性值一致 public String addUser(@Valid User user, BindingResult br) {// 紧跟Valid参数之后写验证结果类 if (br.hasErrors()) { return "user/addUser"; } users.put(user.getUsername(), user); return InternalResourceViewResolver.REDIRECT_URL_PREFIX + "/user/userList"; }
?
修改用户列表页面/jsp/user/userList.jsp添加:<a href="addUserPro">添加用户</a>
添加用户新增页面