如何在spring启动项目中设置验证(org.hibernate.validator.constraints)



我有项目与春季启动,春季mvc和hibernate,我想验证休息参数,我有控制器:

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),但验证没有执行:(,我发送无效参数的请求密码=",请求运行没有错误:(,为什么?我设置验证@NotEmpty密码,如果我设置密码="或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
}

相关内容

最新更新