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