Spring REST APIの検証

Spring REST API検証

Spring MVCでは、@RequestBody@Validの注釈を付けるだけで、検証プロセスが実行されます。

Note
完全なソースコードについては、これを参照してください–Spring Boot Ajax example

P.S Tested with Spring Boot 1.5.1.RELEASE (Spring 4.3.6.RELEASE)

1. JSR 303検証

BeanにJSR303注釈を追加します。

package com.example.model;

import org.hibernate.validator.constraints.NotBlank;

public class SearchCriteria {

    @NotBlank(message = "username can't empty!")
    String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

2. @Valid @RequestBody

Spring REST API、2番目の引数Errorsオブジェクトには、検証の詳細が含まれます。

package com.example.controller;

import com.example.model.AjaxResponseBody;
import com.example.model.SearchCriteria;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class SearchController {

    @PostMapping("/api/search")
    public ResponseEntity search(
        @Valid @RequestBody SearchCriteria search, Errors errors) {

        Result result = new Result();

        //If error, just return a 400 bad request, along with the error message
        if (errors.hasErrors()) {

            // get all errors
            result.setMsg(errors.getAllErrors()
                .stream()
                .map(x -> x.getDefaultMessage())
                .collect(Collectors.joining(",")));

            return ResponseEntity.badRequest().body(result);

        }

        List users = //get users...
        if (users.isEmpty()) {
            result.setMsg("no user found!");
        } else {
            result.setMsg("success");
        }
        result.setResult(users);

        return ResponseEntity.ok(result);

    }

}