Skip to content

Commit

Permalink
validation
Browse files Browse the repository at this point in the history
  • Loading branch information
gao.qiwei committed Jul 9, 2019
0 parents commit 31ec167
Show file tree
Hide file tree
Showing 11 changed files with 335 additions and 0 deletions.
37 changes: 37 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/

### VS Code ###
.vscode/
.iml
mvnw
mvnw.cmd
HELP.md
.idea
.mvn
67 changes: 67 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.soccergao</groupId>
<artifactId>spring-web-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-web-demo</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
<swagger-version>2.9.2</swagger-version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger-version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger-version}</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.soccergao.springwebdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class SpringWebDemoApplication {

public static void main(String[] args) {
SpringApplication.run(SpringWebDemoApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package com.soccergao.springwebdemo.exception;

import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Set;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Set<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
return ex
.getBindingResult()
.getAllErrors()
.stream()
.map(ObjectError::getDefaultMessage)
.collect(Collectors.toSet());
}
}
31 changes: 31 additions & 0 deletions src/main/java/com/soccergao/springwebdemo/service/UserService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.soccergao.springwebdemo.service;

import com.soccergao.springwebdemo.web.dto.User;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class UserService {

public List<User> query() {
return Stream
.of(User.builder().id(1L).username("root").password("root").birthday(LocalDateTime.now()).build(),
User.builder().id(2L).username("root").password("root").birthday(LocalDateTime.now()).build())
.collect(Collectors.toList());

}

public User get(Long userId) {
return User.builder()
.id(userId)
.username("root")
.password("root")
.birthday(LocalDateTime.now())
.build();
}

}
54 changes: 54 additions & 0 deletions src/main/java/com/soccergao/springwebdemo/web/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.soccergao.springwebdemo.web;

import com.fasterxml.jackson.annotation.JsonView;
import com.soccergao.springwebdemo.service.UserService;
import com.soccergao.springwebdemo.web.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/v1/user")
public class UserController {

@Autowired
UserService userService;

@PostMapping
public User save(@Valid @RequestBody User user) {
user.setId(1L);
return user;
}

@JsonView(User.UserDetailView.class)
@GetMapping("/{id:\\d+}")
public User get(@PathVariable Long id) {
return userService.get(id);
}

@JsonView(User.UserSimpleView.class)
@GetMapping
public List<User> query() {
return userService.query();
}


}

@RestController
@RequestMapping("/v2/user")
class UserController2 {
@PostMapping
public User save(@Valid @RequestBody User user, BindingResult errors) {
if (errors != null) {
errors.getAllErrors()
.forEach(error -> System.out.println(error.getDefaultMessage()));
}

user.setId(1L);
return user;
}
}
37 changes: 37 additions & 0 deletions src/main/java/com/soccergao/springwebdemo/web/dto/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.soccergao.springwebdemo.web.dto;

import com.fasterxml.jackson.annotation.JsonView;
import com.soccergao.springwebdemo.web.validator.PasswordCheck;
import lombok.Builder;
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Past;
import java.time.LocalDateTime;

@Data
@Builder
public class User {

@JsonView(UserSimpleView.class)
private Long id;

@JsonView(UserSimpleView.class)
@NotBlank(message = "用户名不能为空")
private String username;

@JsonView(UserDetailView.class)
@PasswordCheck
private String password;

@JsonView(UserDetailView.class)
@Past(message = "生日必须是过去的时间")
private LocalDateTime birthday;

// @JsonView使用方法:
// 1. 使用接口来声明多个视图
// 2. 在pojo的get方法上指定视图
// 3. 在Controller方法上指定视图
public interface UserSimpleView {}
public interface UserDetailView extends UserSimpleView {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package com.soccergao.springwebdemo.web.validator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordValidator.class)
public @interface PasswordCheck {
int value() default 8;

String message() default "密码格式错误";

Class<?>[] groups() default { };

Class<? extends Payload>[] payload() default { };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.soccergao.springwebdemo.web.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
* 该类会交给spring管理
* ConstraintValidator<PasswordCheck, String>中的String是字段的类型
* 如: private String password 中的String;
*/
public class PasswordValidator implements ConstraintValidator<PasswordCheck, String> {

private int value;

@Override
public void initialize(PasswordCheck constraintAnnotation) {
value = constraintAnnotation.value();
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value.length() >= this.value;
}
}
8 changes: 8 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
spring:
application:
name: spring-web-demo

server:
port: 8090
servlet:
context-path: /
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.soccergao.springwebdemo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringWebDemoApplicationTests {

@Test
public void contextLoads() {
}

}

0 comments on commit 31ec167

Please sign in to comment.