Spring验证异常:BindException

时间:2015-03-16 10:53:12

标签: java spring hibernate validation spring-mvc

将表单提交至 addUser 发生控制器异常

  

SEVERE:servlet dispatcherServlet的Servlet.service()引发了异常   org.springframework.validation.BindException:org.springframework.validation.BeanPropertyBindingResult:1个错误   对象' userBean'中的字段错误在现场'电子邮件':被拒绝的价值[你好];代码[Email.userBean.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:codes [userBean.email,email];参数[];默认消息[email]];默认消息[不是虚拟电子邮件地址]       在org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:111)       在org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75)       在org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156)       在org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117)       在org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)       在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)       在org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)       在org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)       在org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)       在org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)       在org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)       在org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)       在javax.servlet.http.HttpServlet.service(HttpServlet.java:710)       在javax.servlet.http.HttpServlet.service(HttpServlet.java:803)       在org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)       在org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)       在org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)       在org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)       在org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)       在org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)       在org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)       在org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)       在org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)       在org.apache.coyote.http11.Http11Protocol $ Http11ConnectionHandler.process(Http11Protocol.java:581)       在org.apache.tomcat.util.net.JIoEndpoint $ Worker.run(JIoEndpoint.java:447)       在java.lang.Thread.run(Thread.java:744)

获取表单的控制器

    @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>

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

1 个答案:

答案 0 :(得分:14)

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

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