一:任务

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);
}

006 使用SpringMVC开发restful API四--用户信息的修复与删除,重在注解的定义的更多相关文章

  1. 003 使用SpringMVC开发restful API--查询用户

    一:介绍说明 1.介绍 2.restful api的成熟度 二:编写Restful API的测试用例 1.引入spring的测试框架 在effective pom中查找 2.新建测试包,测试类 3.测 ...

  2. 004 使用SpringMVC开发restful API二--编写用户详情

    一:编写用户详情服务 1.任务 @PathVariable隐射url片段到java方法的参数 在url声明中使用正则表达式 @JsonView控制json输出内容 二:@PathVariable 1. ...

  3. 007 使用SpringMVC开发restful API五--异常处理

    一:任务 1.任务 Spring Boot中默认的错误机制处理机制 自定义异常处理 二:Spring Boot中的默认错误处理机制 1.目前 浏览器访问的时候, restful 接口主要是根据状态码进 ...

  4. 005 使用SpringMVC开发restful API三--处理创建请求

    一:主要任务 1.说明 @RequestBody 映射请求体到java方法的参数 日期类型参数的处理 @Valid注解 BindingResult验证请求参数的合法性并处理校验结果 二:@Reques ...

  5. 使用Spring MVC开发RESTful API

    第3章 使用Spring MVC开发RESTful API Restful简介 第一印象 左侧是传统写法,右侧是RESTful写法 用url描述资源,而不是行为 用http方法描述行为,使用http状 ...

  6. springmvc/springboot开发restful API

    非rest的url写法: 查询 GET /user/query?name=tom 详情 GET /user/getinfo? 创建 POST /user/create?name=tom 修改 POST ...

  7. ASP.NET Core Web API 开发-RESTful API实现

    ASP.NET Core Web API 开发-RESTful API实现 REST 介绍: 符合REST设计风格的Web API称为RESTful API. 具象状态传输(英文:Representa ...

  8. flask开发restful api系列(8)-再谈项目结构

    上一章,我们讲到,怎么用蓝图建造一个好的项目,今天我们继续深入.上一章中,我们所有的接口都写在view.py中,如果几十个,还稍微好管理一点,假如上百个,上千个,怎么找?所有接口堆在一起就显得杂乱无章 ...

  9. flask开发restful api

    flask开发restful api 如果有几个原因可以让你爱上flask这个极其灵活的库,我想蓝图绝对应该算上一个,部署蓝图以后,你会发现整个程序结构非常清晰,模块之间相互不影响.蓝图对restfu ...

随机推荐

  1. 【原创】大叔经验分享(40)hdfs关闭kerberos

    hadoop.security.authentication: Kerberos -> Simple hadoop.security.authorization: true -> fals ...

  2. ActiveMQ-为什么需要消息中间件?

    消息中间件的优势 UNIX的进程间通信就开始运用消息队列技术,一个进程将数据写入某个特定的队列中,其它进程可以读取队列中的数据,从而实现异步通信.对于如今的分布式系统,消息队列已经演变为独立的消息中间 ...

  3. LINUX用户、组、权限管理和归档压缩、时间、Ping

    一.用户与用户组管理.权限 1.用户文件/etc/passwd 2.用户密码/etc/shadow 3.组文件/etc/group 4.查看用户和组信息命令id 5.添加用户 useradd [-u ...

  4. linux压缩与解压(持续更新)

    压缩 tar cvzf  w.tar.gz  xxx1 xxx2  对应解压:tar xvzf w.tar.gz

  5. swift 实践- 14 -- UIScrollView

    import UIKit class ViewController: UIViewController ,UIScrollViewDelegate{ override func viewDidLoad ...

  6. 信息摘要算法之二:SHA1算法分析及实现

    SHA算法,即安全散列算法(Secure Hash Algorithm)是一种与MD5同源的数据加密算法,该算法经过加密专家多年来的发展和改进已日益完善,现在已成为公认的最安全的散列算法之一,并被广泛 ...

  7. Ftp上传的方法

    using System;using System.Collections.Generic;using System.IO;using System.Net;using System.Text; na ...

  8. 在 Linux 中自动启动 Confluence 6

    在 Linux/Solaris 环境下,最好的办法是对每一个服务进行安装和配置(包括 Confluence),同时配置这些服务权限为他们所在用户需要的服务权限即可, 为实例创建一个 Confluenc ...

  9. Confluence 6 手动运行和修改

    手动运行一个任务 希望手动运行一个计划任务,进入计划任务的列表中,找到你希望手动运行的计划任务,在这个计划任务的边上选择 运行(Run).这个计划任务将会马上执行. 不是所有的计划任务都可以手动运行的 ...

  10. Confluence 6 访问你的宏正文(body)

    请查看 Writing User Macros 页面获得有关如何写用户宏的介绍. 这个页面介绍你可以在用户宏中可以使用的的代码信息. 访问你的宏正文(body) 在你用户宏模板中的 $body 对象可 ...