1.导入jar包()
2.在实体类中对应属性上加注解
@NotEmpty(message="账号不能为空") private String name; @NotEmpty(message="密码不能为空") @Length(min=6,max=12,message="密码在[6-12]之间") private String password; @NotEmpty(message="手机号不能为空") @Pattern(regexp="^1[3|4|5|7|8][0-9]\\d{4,8}$",message="手机号格式不正确") private String phone; @NotNull(message="年龄不能为空") @Digits(integer=2,fraction=2,message="数只能有两个整数") private Integer age; |
3.在控制层接收参数(@Valid User2 user,BindingResult br,这两个参数要靠在一起)
@RequestMapping("register") public String register(@Valid User user,BindingResult br,HttpServletRequest request) { if(br.hasErrors()) { List<FieldError> fieldErrors=br.getFieldErrors(); Map<String,Object> errorMsg=new HashMap<>(); for(FieldError f:fieldErrors) { errorMsg.put(f.getField(), f.getDefaultMessage()); } request.setAttribute("errorMsg", errorMsg); return "forward:/register.jsp"; } System.out.println(user); return "register"; } |
在jsp中显示
<form action="/SpringMVC/user/register" method="post"> name:<input type="text" name="name"/>${errorMsg.name }<br/> password:<input type="password" name="password"/>${errorMsg.password }<br/> phone:<input type="text" name="phone"/>${errorMsg.phone }<br/> age:<input type="text" name="age"/>${errorMsg.age }<br/> photo:<input type="file" name="photo"/>${errorMsg.photo }<br/> <input type="submit" value="提交"/><br/> </form> |