1. Introduce dependencies

<dependency>
    <groupId>org.hibernate.validator</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.10. The Final</version>
</dependency>
Copy the code

2. Define parameter verification exception interceptor

package com.example.demo.exception.global;

import com.alibaba.cola.dto.SingleResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({ConstraintViolationException.class, MethodArgumentNotValidException.class, ServletRequestBindingException.class, BindException.class})
    public SingleResponse<Object> handleValidationException(Exception e) {
        String msg;
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException t = (MethodArgumentNotValidException) e;
            msg = getBindingResultMsg(t.getBindingResult());
        } else if (e instanceof BindException) {
            BindException t = (BindException) e;
            msg = getBindingResultMsg(t.getBindingResult());
        } else if (e instanceof ConstraintViolationException) {
            ConstraintViolationException t = (ConstraintViolationException) e;
            msg = t.getConstraintViolations().stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining(","));
        } else if (e instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException t = (MissingServletRequestParameterException) e;
            msg = t.getParameterName() + "Can't be empty.";
        } else if (e instanceof MissingPathVariableException) {
            MissingPathVariableException t = (MissingPathVariableException) e;
            msg = t.getVariableName() + "Can't be empty.";
        } else {
            msg = "Required parameter missing";
        }
        return SingleResponse.buildFailure(String.valueOf(ErrorCode.PARAMETER_ERROR.getCode()), msg);
    }
    
    private String getBindingResultMsg(BindingResult bindingResult) {
        StringBuilder stringBuilder = new StringBuilder();
        if (bindingResult.hasErrors()) {
            for (ObjectError error : bindingResult.getAllErrors()) {
                stringBuilder.append(error.getDefaultMessage()).append(";"); }}returnstringBuilder.toString(); }}Copy the code

A common API package is recommended here

<dependency>
    <groupId>com.alibaba.cola</groupId>
    <artifactId>cola-component-dto</artifactId>
    <version>4.0.1</version>
</dependency>
Copy the code

3. Verify parameters

package com.example.api.domain.message.dto;

import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import java.util.List;

/ * * * com. Avatar. Socketio. Server domain. Message. Dto * Description: * * * send the message parameters@author jack
 * @date 2021/06/24 5:31 下午
 */
@Data
public class MessageDTO implements Serializable {

    private static final long serialVersionUID = -4201486472018401037L;

    /** * Message content */
    @NotBlank
    private String content;

    /** ** Sender */
    private String sender;

    /** * Receiver */
    @notempty (message = "receiver cannot be empty ")
    private List<String> receiverList;

    /** * namespace */
    @notblank (message = "namespace cannot be empty ")
    private String namespace;
}

Copy the code

4. Test

package com.example.controller.message;

import com.alibaba.cola.dto.SingleResponse;
import com.avatar.api.common.response.PlainResult;
import com.avatar.api.common.utils.ResultUtils;
import com.avatar.socketio.api.domain.message.dto.BroadCastMessageDTO;
import com.avatar.socketio.api.domain.message.dto.MessageDTO;
import com.avatar.socketio.server.service.message.MessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/api/v1/message")
@Slf4j
@RequiredArgsConstructor
public class MessageController {

    @PostMapping("/addMessage")
    public SingleResponse<Object> addMessage(@RequestBody @Validated MessageDTO messageDTO) {
        log.info("messageDTO:{}",messageDTO);
        return SingleResponse.of(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); }}Copy the code

5. @Validatedand@ValidThe difference between

@Validated: The nested verification function cannot be provided separately for method inputs. Cannot be used on member attributes (fields), nor can it prompt the framework for nested validation. Can be nested with the @valid annotation for nested validation.

Valid: cannot provide nested validation on method input arguments alone. Can be used on member attributes (fields) to prompt the validation framework for nested validation. Can be nested with the @valid annotation for nested validation.