休眠验证器不适用于Spring MVC应用程序

时间:2018-10-12 08:51:03

标签: java spring spring-mvc hibernate-validator

我正在第4本书的Spring中跟踪一个示例项目。但是,在第5章中,我被禁止使用冬眠验证器来验证表单提交的值。以下是一些相关代码:

我有一个名为Spitter的模型:

package spittr;


import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;


public class Spitter {

    private Long id;

    @NotNull
    @Size(min=5, max=16)
    private String username;

    @NotNull
    @Size(min=5, max=25)
    private String password;

    @NotNull
    @Size(min=2, max=30)
    private String firstName;

    @NotNull
    @Size(min=2, max=30)
    private String lastName;
    private String email;

    public Spitter() {
    }

    public Spitter(String username, String password, String firstName, String lastName, String email) {
        this(null, username, password, firstName, lastName, email);
    }

    public Spitter(Long id, String username, String password, String firstName, String lastName, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public boolean equals(Object that) {
        return EqualsBuilder.reflectionEquals(this, that, "firstName", "lastName", "username", "password", "email");
    }

    @Override
    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this, "firstName", "lastName", "username", "password", "email");
    }

}

控制器收集表单数据并验证它们:

package spittr.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import spittr.Spitter;
import spittr.data.SpitterRepository;

import javax.validation.Valid;

@Controller
@RequestMapping("/spitter")
public class SpitterController {

    private SpitterRepository spitterRepository;

    @Autowired
    public SpitterController(SpitterRepository spitterRepository) {
        this.spitterRepository = spitterRepository;
    }


    @RequestMapping(value = "register", method = RequestMethod.POST)
    public String processRegistration(@Valid Spitter spitter, Errors errors) {
        System.out.println(errors.hasErrors() + ": has errors...");
        if (errors.hasErrors()){
            return "registerForm";
        }
        spitterRepository.save(spitter);
        return "redirect:/spitter/" + spitter.getUsername();
    }
}

和配置文件(基于Java):

package spittr.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan(
        basePackages = {"spittr"},
        excludeFilters = {
                @Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)
        })
public class RootConfig {
}

SpitterWebInitializer:     软件包spittr.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import spittr.web.WebConfig;

public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[]{RootConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class<?>[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

}

WebConfig     软件包spittr.web;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

build.gradle文件:

apply plugin: 'war'
apply plugin: 'idea'
apply plugin: 'java'
//apply from: 'gretty.plugin'
apply plugin: 'com.bmuschko.tomcat'

buildscript {
    repositories {
        jcenter()
    }

    dependencies {
        classpath 'com.bmuschko:gradle-tomcat-plugin:2.2.2'
    }
}

dependencies {
    compile "org.springframework:spring-webmvc:4.0.7.RELEASE"
    compile "org.springframework:spring-jdbc:4.0.7.RELEASE"
    compile "org.hibernate:hibernate-validator:5.3.2.Final"
    //providedCompile "org.glassfish.web:javax.el:2.2.4"
    // https://mvnrepository.com/artifact/javax.validation/validation-api
    providedCompile group: 'javax.validation', name: 'validation-api', version: '1.1.0.Final'

    compile "javax.servlet:jstl:1.2"
    compile "org.apache.commons:commons-lang3:3.1"
    def tomcatVersion = '7.0.59'
    tomcat "org.apache.tomcat.embed:tomcat-embed-core:${tomcatVersion}",
            "org.apache.tomcat.embed:tomcat-embed-logging-juli:${tomcatVersion}",
            "org.apache.tomcat.embed:tomcat-embed-jasper:${tomcatVersion}"
    providedCompile "javax.servlet.jsp:jsp-api:2.1"
    providedCompile "javax.el:javax.el-api:2.2.4"
    providedCompile 'javax.servlet:javax.servlet-api:3.1.0'
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
    maven { url 'http://maven.springframework.org/release' }
    maven { url 'http://maven.springframework.org/milestone' }
    maven { url 'http://maven.springframework.org/snapshot' }
    maven { url 'http://download.java.net/maven/2' }
    mavenCentral()

}

war {
    baseName = 'spittr'
    version = '0.1.0'
}

tomcat {
    httpPort = 8080
    httpsPort = 8443
    enableSSL = true
//    contextPath = 'sample-app'
}

可以在GitHub上找到完整的项目:https://github.com/zmrenwu/Spittr

我花了几天时间在Google和Stackoverflow上搜索解决方案,但没有运气。

请给我一些帮助,谢谢!

3 个答案:

答案 0 :(得分:1)

我对Gradle并不熟悉,但是我认为,如果您删除此行,它会起作用:

providedCompile group: 'javax.validation', name: 'validation-api', version: '1.1.0.Final' 

至少我用Maven进行了测试,它解决了问题。

答案 1 :(得分:0)

向您的控制器类添加@Validated注释:

@Controller
@Validated
@RequestMapping("/spitter")
public class SpitterController {

...

答案 2 :(得分:0)

hibernate-validator默认情况下使用的是javax.validation:validation-api:jar:1.1.0.Final

[INFO] | +-org.hibernate.validator:hibernate-validator:jar:6.0.12.Final:compile [INFO] | | +-(javax.validation:validation-api:jar:1.1.0.Final:

尝试升级到最新版本javax.validation:validation-api:2.0.1.Final对我有用。