SpringBoot 数据验证


化石原创文章,转载请注明来源并保留原文链接


1、使用Maven,pom文件中加入:

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

2、在需要的field上,比如某个类的一个变量不能为null或者empty

import javax.validation.constraints.NotBlank;

public class Article {
    @NotBlank(message = "title cannot be blank")
    private String title;
}

3、使用到Article实例的地方,用上@valid

import javax.validation.Valid;

public ResponseEntity<?> saveArticle(@Valid @RequestBody Article article) {
}

到此,如果不能通过验证(例子中title如果是null或者trim()后长度为零),那么底层就直接拦住了,saveArticle()不会得到调用。

但是用户收到的信息缺失一个404的错误。这里可以定制处理。

4、写一个继承ResponseEntityExceptionHandler的类

package API;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@SuppressWarnings({"unchecked","rawtypes"})
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler
{
    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
        List<String> details = new ArrayList<>();
        details.add(ex.getLocalizedMessage());
        ErrorResponse error = new ErrorResponse("Server Error", details);
        return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<String> details = new ArrayList<>();
        for(ObjectError error : ex.getBindingResult().getAllErrors()) {
            details.add(error.getDefaultMessage());
        }
        ErrorResponse error = new ErrorResponse("Validation Failed", details);
        return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST);
    }
}

其中的方法handleMethodArgumentNotValid,就是用来处理参数验证错误。

ErrorResponse是一个自定义的类:

package API;

import java.util.List;

public class ErrorResponse {
    private String message;
    private List<String> details;

    public ErrorResponse(String message, List<String> details) {
        super();
        this.message = message;
        this.details = details;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public List<String> getDetails() {
        return details;
    }

    public void setDetails(List<String> details) {
        this.details = details;
    }
}

注意getter一定要写,否则ajax的error回调,responseText是空的json。


化石原创文章,转载请注明来源并保留原文链接


发表评论

电子邮件地址不会被公开。 必填项已用*标注