Spring验证异常:BindException


问题内容

提交表单到 addUser 控制器时发生异常

严重:Servlet调度程序的Servlet.service()抛出异常org.springframework.validation.BindException:org.springframework.validation.BeanPropertyBindingResult:1错误字段’email’上的对象’us​​erBean’中的字段错误:拒绝的值[hello];
代码[Email.userBean.email,Email.email,Email.java.lang.String,Email];
参数[org.springframework.context.support.DefaultMessageSourceResolvable:代码[userBean.email,email];
参数[];
默认消息[电子邮件]];org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:111)上的默认消息)在org。

获取表格的控制器

    @RequestMapping(method = RequestMethod.GET, value = "register")
public String addUser(Model model) {
    if (!model.containsAttribute("wrongLink")) {
        System.out.println("not wrong Link");
        model.addAttribute(new UserBean());
    } else {
        System.out.println("wrong Link");
    }
    return "user/register";
}

控制器过帐表格

@RequestMapping(method = RequestMethod.POST, value = "register")
public String addUser(@Valid UserBean userBean, Model model,
        RedirectAttributes redirectAttrs, BindingResult bindingResult) {
    System.out.println("in addUser form");
    if (bindingResult.hasErrors()) {
        System.out.println("ERROR in user Form");
        return "user/edit";
    }
    return "redirect:/users/" + user.getDisplayName();
}

UserBean类

import org.hibernate.validator.constraints.Email;
public class UserBean {

private Integer id;

@Email(message = "Not a vaild Email Address")
private String email;
//getter and setter
}

形成

<div id="container">
    <sf:form method="POST" modelAttribute="userBean">
            <div class="form">
                <sf:input path="email" type="text" id="email"
                    placeholder="email address" />
                <sf:errors path="email" cssClass="error" />
                <input class="send submit" type="submit" name="submit_first"
                    id="submit_first" value="" />
            </div>
    </sf:form>
</div>

spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://www.springframework.org/schema/beans     
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">

<context:component-scan base-package="com.example" />

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="${smtp.host}" />
    <property name="port" value="${smtp.port}" />
    <property name="username" value="${smtp.username}" />
    <property name="password" value="${smtp.password}" />
    <property name="javaMailProperties">
        <props>
            <!-- Use SMTP transport protocol -->
            <prop key="mail.transport.protocol">smtp</prop>
            <!-- Use SMTP-AUTH to authenticate to SMTP server -->
            <prop key="mail.smtp.auth">true</prop>
            <!-- Use TLS to encrypt communication with SMTP server -->
            <prop key="mail.smtp.starttls.enable">true</prop>
            <prop key="mail.debug">true</prop>
        </props>
    </property>
</bean>

<bean id="alertMailMessage" class="org.springframework.mail.SimpleMailMessage">
    <property name="from" value="${alertMailMessage.from}" />
    <property name="to" value="${alertMailMessage.to}" />
    <property name="subject" value="${alertMailMessage.subject}" />
</bean>

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="1000000" />
</bean>


<bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<mvc:resources mapping="/**" location="/resources/" />

<mvc:annotation-driven />

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>/WEB-INF/properties/database.properties</value>
            <value>/WEB-INF/properties/smtp.properties</value>
        </list>
    </property>
</bean>

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.user}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.example.model" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
        </props>

    </property>
</bean>


<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

为什么在输入无效电子邮件时会出现此异常,而不是必须执行验证。


问题答案:

在控制器的addUser方法中,您BindingResult需要紧接在bean之后:

public String addUser(@Valid UserBean userBean, BindingResult bindingResult,
                      Model model, RedirectAttributes redirectAttrs) {
    ...
}