006 使用SpringMVC开发restful API四--用户信息的修复与删除,重在注解的定义
一:任务
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四--用户信息的修复与删除,重在注解的定义的更多相关文章
- 003 使用SpringMVC开发restful API--查询用户
一:介绍说明 1.介绍 2.restful api的成熟度 二:编写Restful API的测试用例 1.引入spring的测试框架 在effective pom中查找 2.新建测试包,测试类 3.测 ...
- 004 使用SpringMVC开发restful API二--编写用户详情
一:编写用户详情服务 1.任务 @PathVariable隐射url片段到java方法的参数 在url声明中使用正则表达式 @JsonView控制json输出内容 二:@PathVariable 1. ...
- 007 使用SpringMVC开发restful API五--异常处理
一:任务 1.任务 Spring Boot中默认的错误机制处理机制 自定义异常处理 二:Spring Boot中的默认错误处理机制 1.目前 浏览器访问的时候, restful 接口主要是根据状态码进 ...
- 005 使用SpringMVC开发restful API三--处理创建请求
一:主要任务 1.说明 @RequestBody 映射请求体到java方法的参数 日期类型参数的处理 @Valid注解 BindingResult验证请求参数的合法性并处理校验结果 二:@Reques ...
- 使用Spring MVC开发RESTful API
第3章 使用Spring MVC开发RESTful API Restful简介 第一印象 左侧是传统写法,右侧是RESTful写法 用url描述资源,而不是行为 用http方法描述行为,使用http状 ...
- springmvc/springboot开发restful API
非rest的url写法: 查询 GET /user/query?name=tom 详情 GET /user/getinfo? 创建 POST /user/create?name=tom 修改 POST ...
- ASP.NET Core Web API 开发-RESTful API实现
ASP.NET Core Web API 开发-RESTful API实现 REST 介绍: 符合REST设计风格的Web API称为RESTful API. 具象状态传输(英文:Representa ...
- flask开发restful api系列(8)-再谈项目结构
上一章,我们讲到,怎么用蓝图建造一个好的项目,今天我们继续深入.上一章中,我们所有的接口都写在view.py中,如果几十个,还稍微好管理一点,假如上百个,上千个,怎么找?所有接口堆在一起就显得杂乱无章 ...
- flask开发restful api
flask开发restful api 如果有几个原因可以让你爱上flask这个极其灵活的库,我想蓝图绝对应该算上一个,部署蓝图以后,你会发现整个程序结构非常清晰,模块之间相互不影响.蓝图对restfu ...
随机推荐
- Jmeter下载安装配置及使用(windows)
1 前言 仅作为记录使用. 2 步骤 2.1 下载地址:http://jmeter.apache.org/download_jmeter.cgi 2.2 选择binary版本即可:apache-jme ...
- python元组,集合类型,及字典补充
一.元组 元组与列表基本相同,不同之处在于元组只能存不能取,当多个值没有改的需求时,用元组更合适 元组的基本操作 1.创建元组: t = (1, 2, 3, 4, 2,4,) t = (1,) #单个 ...
- linux与window互传文件
首先我们的目标是把一个很大的文件传到linux中,所以我们先要让linux节点开启ftp服务 FTP 10.1.61.212 如果对方没有开启FTP服务,那么这个命令就不会有效果. 1.开启xftp ...
- kindeditor用法简单介绍(转)
1,首先去官网下载http://www.kindsoft.net/ 2,解压之后如图所示: 由于本人做的是用的是JSP,所以ASP,PHP什么的就用不上了,直接把那些去掉然后将整个文件夹扔进Myecl ...
- Confluence 6 配置白名单
Confluence 管理员可以通过添加 URLs 到白名单选择出入的链接和使用 RSS 宏,HTML 包含宏和小工具中的内容. 如果一个内容被添加到 Confluence 系统中,但是这个 URLs ...
- usrp使用
首先打开linux 输入uhd_find_divice gqrx
- 一.定时任务详解https://i.cnblogs.com/EditPosts.aspx
定时任务的详解 h每小时运行 d每天运行 w每周运行 m每个月运行 中毒时查看系统定时任务是否有病毒的脚本. crontab -l 查看用户的定时任务 crontab -e 进入编辑界面增加 ...
- mybatis的批量删除操作
需求描述:将符合某条件的几条记录删除 解决思路:对于多个id,可以使用sql关键词 in ,只要满足数据库的id在你的id集合或者list中,就删除,从而实现批量删除.循环delete方法是在是low ...
- PLC漏洞问题
1.PLC采用大多是经过裁剪的实时操作系统,比如像linux RT.QNX.VxWorks等,这些实时操作系统广泛应用在通信.军事.航天.等工程领域,但是随之工业与网络的互连爆发出很多问题,常见的PL ...
- cf1132G 线段树解分区间LIS(一种全新的线段树解LIS思路)+单调栈
/* 给定n个数的数列,要求枚举长为k的区间,求出每个区间的最长上升子序列长度 首先考虑给定n个数的数列的LIS求法:从左往右枚举第i点作为最大点的贡献, 那么往左找到第一个比a[i]大的数,设这个数 ...