【问题标题】:Hibernate Validation. Messages displayed as identifiers of them休眠验证。消息显示为它们的标识符
【发布时间】:2017-04-10 11:54:09
【问题描述】:

我正在为 Hibernate 验证和自定义错误消息而苦苦挣扎。 就我而言,我对注册表单和消息包进行了简单的验证。我正在尝试使用这些消息,但每当出现错误时,它们就会在页面上显示为 {error.identifier}。我调试了代码,发现这条消息已经传递给了 Errors 对象 下面的描述。请帮忙。我到处找。

Page screenshot

以上消息仅由 Thymeleaf <p th:text="#{password.constraint}"></p> 撰写 MvcConfig.java:

@Bean
public LocaleResolver localeResolver() {
    return new CookieLocaleResolver();
}



@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
}


@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(localeChangeInterceptor());
}
@Bean(name = "messageSource")
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new 
    ReloadableResourceBundleMessageSource();
    messageSource.setBasename("/i18n/messages");
    messageSource.setDefaultEncoding("UTF-8");
    messageSource.setFallbackToSystemLocale(false);
    messageSource.setCacheSeconds(0);
    return messageSource;
}

@Bean
public ValidatorFactory validator() {
    LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
    factory.setValidationMessageSource(messageSource());
    return factory;
}

SignupForm.java:

import org.hibernate.validator.constraints.*;
import org.z1key.projects.entity.Role;
import org.z1key.projects.entity.User;

import javax.validation.constraints.Pattern;

@FieldMatch(first = "password", second = "verifyPassword", message = 
"Passwords are different.")
public class SignupForm {

private static final String NOT_BLANK_MESSAGE = "{notBlank.message}";
private static final String EMAIL_MESSAGE = "{email.constraint}";
private static final String PASSWORD_MESSAGE = "{password.constraint}";

@NotBlank
@Length(min = 5, max = 25)
@Pattern(regexp = "^[A-Za-z\\d]+$", message = "{login.constraint}")
private String login;

@NotBlank(message = NOT_BLANK_MESSAGE)
@Email(message = EMAIL_MESSAGE)
private String email;

@NotBlank(message = SignupForm.NOT_BLANK_MESSAGE)
@Length(min = 6, max = 40)
@Pattern(regexp = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]+$", message = PASSWORD_MESSAGE)
private String password;

private String verifyPassword;

...Getters & Setters

项目结构:Project Structure screenshot pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.z1key.projects</groupId>
<artifactId>library</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<dependencies>
    <!-- WEB -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Thymeleaf -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>nz.net.ultraq.thymeleaf</groupId>
        <artifactId>thymeleaf-layout-dialect</artifactId>
        <version>2.1.2</version>
    </dependency>
    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>3.0.2.RELEASE</version>
    </dependency>

    <!-- Security-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- JPA -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <!-- Session -->
    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session</artifactId>
        <version>1.3.0.RELEASE</version>
    </dependency>
    <!-- Redis -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

    <!-- JDBC -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!-- TEST -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- jUnit -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <!-- Connection Pool -->
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
    </dependency>

    <!-- MySQL driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.5</version>
    </dependency>

    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.9.3</version>
    </dependency>
</dependencies>

<name>library</name>
<url>http://maven.apache.org</url>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <start-class>org.z1key.projects.config.Application</start-class>
    <thymeleaf.version>3.0.5.RELEASE</thymeleaf.version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
    <finalName>${project.artifactId}</finalName>
    <outputDirectory>${CATALINA_HOME}/webapps/${project.artifactId}</outputDirectory>
    <plugins>
        <!-- Tomcat plugin -->
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
            <artifactId>tomcat7-maven-plugin</artifactId>
            <version>2.2</version>
            <configuration>
                <url>http://localhost:8080/manager/text</url>
                <server>TomcatServer</server>
                <username>z1key</username>
                <password>z1key</password>
                <warFile>target/${project.artifactId}.war</warFile>
                <path>/${project.artifactId}</path>
                <update>true</update>
            </configuration>
        </plugin>
        <!-- Boot Maven plugin-->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!-- Move resources for SpringBoot-->
        <plugin>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.6</version>
            <executions>
                <execution>
                    <id>copy-resources</id>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy-resources</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${basedir}/target/classes/static</outputDirectory>
                        <resources>
                            <resource>
                                <directory>src/main/webapp</directory>
                                <filtering>true</filtering>
                            </resource>
                        </resources>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

我还将 ValidationMessages.properties 添加到具有相同内容的资源文件夹中,并且消息被捕获并显示在页面上。但是询问如何在本地化的 messageSource 包中调用它。因为 @Bean validator() 不会产生任何影响。也许需要在某个地方注入这个 bean?

【问题讨论】:

    标签: java hibernate validation spring-boot


    【解决方案1】:

    我是新手,在混合不同来源的解决方案时犯了错误。解决方案非常简单和愚蠢。需要@Override 方法getValidator() 的扩展超类WebMvcConfigurerAdapter 而不是在那里定义@Bean validator():

    @Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
    ...
    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
        factory.setValidationMessageSource(messageSource());
        return factory;
    }
    ...
    

    我不会删除问题。也许它会对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      相关资源
      最近更新 更多