Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Validation Exception : BindException

on submitting form to addUser controller exception occured

SEVERE: Servlet.service() for servlet dispatcherServlet threw exception org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'userBean' on field 'email': rejected value [hello]; codes [Email.userBean.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [userBean.email,email]; arguments []; default message [email]]; default message [Not a vaild Email Address] at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:111) at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:75) at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:156) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:117) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:744)

Controller for getting Form

    @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";
}

Controller to post form

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

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
}

Form

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

why this exception is coming on entering invalid email rather than validation has to be performed.

like image 407
kartikag01 Avatar asked Mar 16 '15 10:03

kartikag01


People also ask

What is BindException in spring?

public class BindException extends Exception implements BindingResult. Thrown when binding errors are considered fatal. Implements the BindingResult interface (and its super-interface Errors ) to allow for the direct analysis of binding errors. As of Spring 2.0, this is a special-purpose class.

What is a binding exception?

BindException is an exception that is thrown when there is an error caused in binding when an application tries to bind a socket to a local address and port.

How do I use BindingResult in spring boot?

BindingResult holds the result of a validation and binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring fails to validate the object and throws an exception.


1 Answers

In your controller's addUser method, your BindingResult needs to be immediately after the bean:

public String addUser(@Valid UserBean userBean, BindingResult bindingResult,
                      Model model, RedirectAttributes redirectAttrs) {
    ...
}
like image 195
David Lavender Avatar answered Oct 29 '22 23:10

David Lavender