如何在 spring 引导项目中为 rest 设置验证 (org.hibernate.validator.constraints)?

How can to set validation (org.hibernate.validator.constraints) for rest in spring boot project?

我有 spring boot、spring mvc 和 hibarnate 的项目,我想验证其余参数,我有控制器:

import domain.User;
import service.UserService;
import validate.Email;
import org.apache.log4j.Logger;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.ws.rs.FormParam;
import java.util.ArrayList;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/registration", method = RequestMethod.POST)
    public @ResponseBody Boolean registration(@NotEmpty @FormParam("login") String login,
                                @NotEmpty @FormParam("password") String password,
                                @Email(canBeNullOrEmpty = true) @FormParam("email") String email) {
        logger.debug("method registration with params login = " + login
                + ", password = " + password + ", email = " + email);
        return !userService.findByLoginAndPassword(login, password)
                && userService.addUser(new User(login, password, email));
    }

}

和我的 build.gradle:

apply plugin: 'war'
apply plugin: 'spring-boot'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.8.RELEASE")
    }
}

ext {
    springVersion = '4.1.5.RELEASE'
    jacksonVersion = '2.5.3'
}

sourceCompatibility = 1.5

repositories {
    mavenCentral()
}

dependencies {

    compile 'javax.validation:validation-api:1.1.0.Final'
    compile "org.hibernate:hibernate-validator:5.1.3.Final"

    compile "org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion"

    compile 'javax.ws.rs:javax.ws.rs-api:2.0.1'

    compile 'org.postgresql:postgresql:9.3-1101-jdbc41'

    compile "com.fasterxml.jackson.core:jackson-core:$jacksonVersion"
    compile "com.fasterxml.jackson.core:jackson-databind:$jacksonVersion"

    compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"

}

所以,我为我的用户编写了注册,并为其余参数添加了验证(@NotEmpty 用于登录名和密码,@Email),但是验证没有执行 :(,我发送的请求带有无效的参数 password=""并且请求运行没有错误 :(,为什么?我为密码设置了验证 @NotEmpty,如果我设置了 password="" 或 null,我一定会看到错误!因为设置了验证。请帮助我。

不对方法参数执行验证。只需将它们移动到您用 @Valid@ModelAttributes 注释的 POJO 中,就可以了。

类似

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public @ResponseBody Boolean registration(@Valid FooBar fooBar) {
}

static class FooBar {

  @NotEmpty
  String login;

  @NotEmpty
  String password;

  @Email(canBeNullOrEmpty = true)
  String email;

  // getter & setter

}