Spring REST API Validation

摘要: In Spring MVC, just annotate a @Valid on the @RequestBody to fire the validation process.

In Spring MVC, just annotate a @Valid on the @RequestBody to fire the validation process.

Note
For complete source code, please refer to this – Spring Boot Ajax example

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

1. JSR 303 Validation

Add JSR303 annotations on a bean.

package com.mkyong.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

A Spring REST API, the second argument Errors object will contains the validation detail.

package com.mkyong.controller;
import com.mkyong.model.AjaxResponseBody;
import com.mkyong.model.SearchCriteria;
import com.mkyong.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<User> users = //get users...
        if (users.isEmpty()) {
            result.setMsg("no user found!");
        } else {
            result.setMsg("success");
        result.setResult(users);
        return ResponseEntity.ok(result);

References

  1. JSR 303: Bean Validation
  2. Spring Boot Ajax example

上一篇: VirtualBox Copy and Paste between host and guest machine
下一篇: How to convert JavaScript Array to JSON
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号