Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC form validation not working

I am using Spring 4. My form contains the following variables:

@NotNull
@Email
private String email;
@NotNull
private String firstName;
@NotNull
private String lastName;
@Digits(fraction = 0, integer = 10)
private String phoneNo;
@NotNull
private String role;

My controller:

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ModelAndView add(@ModelAttribute("user") @Valid UserBean user, BindingResult result) {
    String message;
    if (result.hasErrors() && user != null)
        return new ModelAndView("userAdd");
    else {
        userService.addUser(user);
        message = "Successfully added user";
    }
    return new ModelAndView("success", "message", message);
    }

    @RequestMapping(value = "/register")
    public ModelAndView register(@ModelAttribute("user") UserBean user, BindingResult result) {
    List<String> roles = new ArrayList<String>();
    roles.add("Receiver");
    roles.add("Resolver");
    roles.add("Logger");
    Map<String, List<String>> model = new HashMap<String, List<String>>();
    model.put("roles", roles);
    return new ModelAndView("userAdd", "model", model);
    }
}

My jsp:

<c:url var="userAdd" value="user/add.do" />
    <sf:form method="post" action="${userAdd}" modelAttribute="user">
        <table>
            <tr>
                <td>First Name</td>
                <td><sf:input path="firstName" /><br /> <sf:errors
                        path="firstName" cssClass="error" /></td>
            </tr>
            <tr>
                <td>Last Name</td>
                <td><sf:input path="lastName" /><br /> <sf:errors
                        path="lastName" cssClass="error" /></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><sf:input path="email" /><br /> <sf:errors
                        path="email" cssClass="error" /></td>
            </tr>
            <tr>
                <td>Phone No.</td>
                <td><sf:input path="phoneNo" /><br /> <sf:errors
                        path="phoneNo" cssClass="error" /></td>
            </tr>
            <tr>
                <td>Role</td>
                <td><sf:select path="role" items="${model.roles}" /><br /> <sf:errors
                        path="role" cssClass="error" /></td>
            </tr>
            <tr>
                <td><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    </sf:form>

When I leave the the inputs blank, the form does not validate and does not throw any error. The BindingResult does not have any errors in it.

My libraries are: Libraries

My dispatcher-serlvet.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- Scans for annotated @Controllers in the classpath -->
    <context:component-scan base-package="com.mj.cchp.controller">
        <context:include-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <bean id="myBeansValidator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
    <mvc:annotation-driven validator="myBeansValidator" />
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

My applicationContext is:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- Scans for annotated @Controllers in the classpath -->
    <context:component-scan base-package="com.mj.cchp">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.ibm.db2.jcc.DB2Driver" />
        <property name="url" value="jdbc:db2://172.16.2.181:60000/CCHP" />
        <property name="username" value="db2inst1" />
        <property name="password" value="db2inst1" />
    </bean> 
</beans>

My web.xml is:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>CCHP</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/application-context.xml</param-value>
    </context-param>
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
like image 277
khateeb Avatar asked Jan 31 '14 10:01

khateeb


3 Answers

You need to add

<bean id="myBeansValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />

and

<mvc:annotation-driven validator="myBeansValidator">

and

    <!-- Hibernate Validator -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.2.0.Final</version>
    </dependency>

Should work!

like image 102
Mannekenpix Avatar answered Oct 30 '22 14:10

Mannekenpix


I had a similar problem and in my case it was sufficient to just add dependency for hibernate validator: org.hibernate:hibernate-validator:5.2.4.Final.

The validation is done by LocalValidatorFactoryBean bean and documentation about it comes handy (here).

Yet at the same time it is worth mentioning that you do not have to instantiate LocalValidatorFactoryBean explicitly as long as you use @EnableWebMvc annotation : http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-validation

By default use of @EnableWebMvc or automatically registers Bean Validation support in Spring MVC through the LocalValidatorFactoryBean when a Bean Validation provider such as Hibernate Validator is detected on the classpath.

Hope this helps.

like image 32
Witold Kaczurba Avatar answered Oct 30 '22 14:10

Witold Kaczurba


I faced the same problem. I resolved by adding below statement in dispatcher-serlvet.xml file.

<mvc:annotation-driven />
like image 33
Hari Krishna Avatar answered Oct 30 '22 13:10

Hari Krishna