一:任务
1.任务
常用的验证注解
自定义返回消息
自定义校验注解
二:Hibernate Validator
1.常见的校验注解
2.程序
测试类
1 /** 2 * @throws Exception 3 * 更新程序,主要是校验程序的验证 4 * 5 */ 6 @Test 7 public void whenUpdateSuccess() throws Exception { 8 //JDK1.8的特性 9 Date date=new Date(LocalDateTime.now().plusYears(1). 10 atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); 11 System.out.println(date.getTime()); 12 String content="{\"id\":\"1\",\"username\":\"tom\",\"password\":null,\"birthday\":"+date.getTime()+"}"; 13 String result=mockMvc.perform(MockMvcRequestBuilders.put("/user/1") 14 .contentType(MediaType.APPLICATION_JSON_UTF8) 15 .content(content)) 16 .andExpect(MockMvcResultMatchers.status().isOk()) 17 .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")) 18 .andReturn().getResponse().getContentAsString(); 19 System.out.println("result="+result); 20 }
User.java
1 package com.cao.dto; 2 3 import java.util.Date; 4 5 import javax.validation.constraints.Past; 6 7 import org.hibernate.validator.constraints.NotBlank; 8 9 import com.fasterxml.jackson.annotation.JsonView; 10 11 public class User { 12 //接口 13 public interface UserSimpleView {}; 14 public interface UserDetailView extends UserSimpleView {}; //继承之后,可以展示父的所有 15 16 private String username; 17 18 @NotBlank 19 private String password; 20 private String id; 21 private Date birthday; 22 23 @JsonView(UserSimpleView.class) 24 public String getUsername() { 25 return username; 26 } 27 public void setUsername(String username) { 28 this.username = username; 29 } 30 31 @JsonView(UserDetailView.class) 32 public String getPassword() { 33 return password; 34 } 35 public void setPassword(String password) { 36 this.password = password; 37 } 38 39 @JsonView(UserSimpleView.class) 40 public String getId() { 41 return id; 42 } 43 public void setId(String id) { 44 this.id = id; 45 } 46 47 @Past 48 @JsonView(UserSimpleView.class) 49 public Date getBirthday() { 50 return birthday; 51 } 52 public void setBirthday(Date birthday) { 53 this.birthday = birthday; 54 } 55 56 }
控制类
1 @PutMapping("/{id:\\d+}") 2 public User update(@Valid @RequestBody User user,BindingResult errors){ 3 if(errors.hasErrors()) { 4 errors.getAllErrors().stream().forEach(error->{ 5 FieldError fieldError=(FieldError)error; 6 String message=fieldError.getField()+" : "+fieldError.getDefaultMessage(); 7 System.out.println(message); 8 } 9 ); 10 11 } 12 13 System.out.println(user.getId()); 14 System.out.println(user.getUsername()); 15 System.out.println(user.getPassword()); 16 System.out.println(user.getBirthday()); 17 18 user.setId("1"); 19 return user; 20 }
效果:
3.完善,自定义提示信息
打印的提示信息是英文的,这里提示中文的
在类上进行定义
1 package com.cao.dto; 2 3 import java.util.Date; 4 5 import javax.validation.constraints.Past; 6 7 import org.hibernate.validator.constraints.NotBlank; 8 9 import com.fasterxml.jackson.annotation.JsonView; 10 11 public class User { 12 //接口 13 public interface UserSimpleView {}; 14 public interface UserDetailView extends UserSimpleView {}; //继承之后,可以展示父的所有 15 16 private String username; 17 18 @NotBlank(message="密码不能为空") 19 private String password; 20 private String id; 21 private Date birthday; 22 23 @JsonView(UserSimpleView.class) 24 public String getUsername() { 25 return username; 26 } 27 public void setUsername(String username) { 28 this.username = username; 29 } 30 31 @JsonView(UserDetailView.class) 32 public String getPassword() { 33 return password; 34 } 35 public void setPassword(String password) { 36 this.password = password; 37 } 38 39 @JsonView(UserSimpleView.class) 40 public String getId() { 41 return id; 42 } 43 public void setId(String id) { 44 this.id = id; 45 } 46 47 @Past(message="生日必须是过去的时间") 48 @JsonView(UserSimpleView.class) 49 public Date getBirthday() { 50 return birthday; 51 } 52 public void setBirthday(Date birthday) { 53 this.birthday = birthday; 54 } 55 56 }
效果
三:自定义校验注解
1.新建一个Annotation
2.程序
校验类
1 package com.cao.validator; 2 3 import java.lang.annotation.ElementType; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6 import java.lang.annotation.Target; 7 8 import javax.validation.Constraint; 9 import javax.validation.Payload; 10 11 @Target({ElementType.METHOD,ElementType.FIELD}) 12 @Retention(RetentionPolicy.RUNTIME) 13 @Constraint(validatedBy = { MyContraintValidator.class }) 14 public @interface MyConstraint { 15 //必写 16 String message() default "{org.hibernate.validator.constraints.NotBlank.message}"; 17 Class<?>[] groups() default { }; 18 Class<? extends Payload>[] payload() default { }; 19 // 20 }
校验处理类
1 import javax.validation.ConstraintValidatorContext; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 5 import com.cao.service.HelloService; 6 import com.cao.service.impl.HelloServiceImpl; 7 8 public class MyContraintValidator implements ConstraintValidator<MyConstraint,Object> { 9 10 //这个校验中可以注入spring容器中的任何东西 11 @Autowired 12 public HelloService hello; 13 14 @Override 15 public void initialize(MyConstraint constraintAnnotation) { 16 System.out.println("my constraint init"); 17 } 18 19 @Override 20 public boolean isValid(Object value, ConstraintValidatorContext context) { 21 hello.greeting("tomm"); 22 System.out.println(value); 23 return false; 24 } 25 26 }
注入使用的服务
1 package com.cao.service; 2 3 public interface HelloService { 4 public String greeting(String name); 5 }
1 package com.cao.service.impl; 2 3 import org.springframework.stereotype.Service; 4 5 import com.cao.service.HelloService; 6 7 //成为Spring容器中的服务了 8 @Service 9 public class HelloServiceImpl implements HelloService { 10 11 @Override 12 public String greeting(String name) { 13 System.out.println("greeting hello"); 14 return "hello "+name; 15 } 16 17 }
使用,放在User.java上
@MyConstraint(message="这是一个测试") private String username;
测试类
1 /** 2 * @throws Exception 3 * 更新程序,主要是校验程序的验证 4 * 5 */ 6 @Test 7 public void whenUpdateSuccess() throws Exception { 8 //JDK1.8的特性 9 Date date=new Date(LocalDateTime.now().plusYears(1). 10 atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); 11 System.out.println(date.getTime()); 12 String content="{\"id\":\"1\",\"username\":\"Bob\",\"password\":null,\"birthday\":"+date.getTime()+"}"; 13 String result=mockMvc.perform(MockMvcRequestBuilders.put("/user/1") 14 .contentType(MediaType.APPLICATION_JSON_UTF8) 15 .content(content)) 16 .andExpect(MockMvcResultMatchers.status().isOk()) 17 .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")) 18 .andReturn().getResponse().getContentAsString(); 19 System.out.println("result="+result); 20 }
效果
四:用户删除
1.程序
测试类
1 /** 2 * 删除程序,主要是校验程序的验证 3 * @throws Exception 4 */ 5 @Test 6 public void whenDeleteSuccess() throws Exception { 7 mockMvc.perform(MockMvcRequestBuilders.delete("/user/1") 8 .contentType(MediaType.APPLICATION_JSON_UTF8)) 9 .andExpect(MockMvcResultMatchers.status().isOk()); 10 }
控制类
1 @DeleteMapping("/{id:\\d+}") 2 public void delete(@PathVariable String id){ 3 System.out.println("id="+id); 4 }
原文地址:https://www.cnblogs.com/juncaoit/p/9710464.html
时间: 2024-10-08 17:27:37