Valid validation, exception unified interception, JackSon manually returning json data

Posted by trial_end_error on Fri, 12 Nov 2021 11:26:57 +0100

  1. Valid validation
    1.1 Valid basic validation
    The original judgment is more completed by the programmer writing logic code. Now it can be completed by annotation. First, we need to add a new maven driver:
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>2.0.1.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>6.2.0.Final</version>
</dependency>

Note: the first driver is java's own verification rules, and the second driver is a verification method provided by hibernate. If only java's own verification rules are used, there is no need to introduce the second driver. Later, we will see different annotation verification brought by the two drivers.

Next, let's make a basic demonstration, for example:

@GetMapping("/test")
@ResponseBody
public String test(@Valid User user) {
    System.out.println("user=" + user);
    return "Hello World!";
}

Here, we can add @ Valid validation before the received vo object, and add corresponding annotations on the vo object attribute header to complete the validation operation, for example:

public class User {
    @Min(value = 1, message = "Primary key id Must be greater than 0")
    private int id;
    @NotBlank(message = "Name cannot be empty")
    @Size(min = 6, max = 10, message = "size Name must be at 6~10 Between bits")
    private String username;
    ......
}

Next, we pass only username through the get request:
http://localhost:8080/check?username=thinknovo
Then we see the following error message on the page:

If we want the returned json error message, we need to manually create an ExceptionHandler, for example:

@ExceptionHandler
@ResponseBody
public Map<String, Object> check(Exception e) {
    e.printStackTrace();
    Map<String, Object> map = new HashMap<>();
    map.put("code", 500);
    map.put("msg", e.getMessage());
    return map;
}

Finally, we can see the json data returned by the page:
{“msg”:“org.springframework.validation.BeanPropertyBindingResult: 1 errors\nField error in object ‘user’ on field ‘id’: rejected value [0]; codes [Min.user.id,Min.id,Min.int,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.id,id]; arguments []; default message [id],1]; default message [primary key ID must be greater than 0], "code": 500}

1.2 common annotations (including Java itself and Hibernate authentication annotations):
@Null
Restrict the data passed by the front end to be null only

@NotNull
The data passed by the restriction front end must not be null

@AssertFalse
The data passed by the restriction front end must be false

@AssertTrue
The data passed by the restriction front end must be true

@DecimalMax(value)
The data passed by the restriction front end must be a number no greater than the specified value

@DecimalMin(value)
The data passed by the restriction front end must be a number not less than the specified value

@Digits(integer,fraction)
The data transferred from the front end must be a decimal (check the decimal point), and the number of digits in the integer part cannot exceed integer and the number of digits in the decimal part cannot exceed fraction

@Future
Restrict front-end transfer data must be a future date

@Max(value)
The data passed by the restriction front end must be a number no greater than the specified value

@Min(value)
The data passed by the restriction front end must be a number not less than the specified value

@Past
Restrict front-end transfer data must be a past date

@Pattern(value)
Restrict the data passed by the front end to conform to the specified regular expression

@Size(max,min)
Limit the length of data characters transmitted by the front end to be between min and max

@Past
Verify that the data (date type) passed by the front end is earlier than the current time

@NotEmpty
Verify that the data passed by the front end is not null and empty (the string length is not 0 and the collection size is not 0)

@NotBlank
Verify that the data passed by the front end is not empty (not null, and the length is 0 after removing the first space). Unlike @ NotEmpty, @ NotBlank is only applied to strings, and the spaces of strings will be removed during comparison

@Email
Verify that the data transmitted by the front end is email. You can also specify a custom email format through regular expression and flag

  1. Exception unified interception
@ControllerAdvice
@ResponseBody
public class ExceptionControllerAdvice {
    @ExceptionHandler
    @ResponseBody
    public Map<String, Object> check(Throwable e) {
        e.printStackTrace();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", e.getMessage());
        return map;
    }
}

Define an exception interception class, just like spring MVC, and then directly encapsulate the message information of the exception in the msg field, so that when an error is thrown, the json data of an error message will be returned, for example:

  1. JackSon returns json data manually
    In some cases, we need to manually create a json object return instead of relying entirely on the automatic return of spring MVC. At this time, we can manually write JackSon's json conversion:
Map<String, Object> map = new HashMap<>();
map.put("code", 500);
map.put("msg", "The user is not logged in and cannot use this function");
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(map);

If you need to manually convert a jsonStr into a java class object, you can do it in the following way:

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonStr, User.class);

Topics: Java JSON Spring