Announcement Announcement Module
Collapse
No announcement yet.
Spring MVC 3 Validation Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring MVC 3 Validation

    Hi,

    I am facing issues in implementing Spring MVC 3 validation. The validation method is called, but no error message is displayed in JSP. Please help me.

    Below are my codes:

    Form Bean
    Code:
    public class LoginFormBean {
       private String username;
       private String password;
       // ... And their getters/setters
    }
    Validator
    Code:
    public class LoginFormValidator implements Validator {
        public boolean supports(Class<?> clazz) {
    	return LoginFormBean.class.isAssignableFrom(clazz);
        }
    
        public void validate(Object target, Errors errors) {
    	final LoginFormBean loginForm = (LoginFormBean) target;
    	if (StringUtils.isBlank(loginForm.getUsername())) {
    	    errors.rejectValue("username", "ERR-10001");
    	}
            if (StringUtils.isBlank(loginForm.getPassword())) {
    	    errors.rejectValue("password", "ERR-10002");
    	}
        }
    }
    Controller
    Code:
    @Controller
    public class LoginController {
        @Autowired
        @Qualifier("loginFormValidator")
        private LoginFormValidator formValidator;
        
        @InitBinder
        public void initBinder(WebDataBinder dataBinder) {
    	dataBinder.setValidator(formValidator);
        }
    
        public String handleLogin(@ModelAttribute("loginFormBean") final LoginFormBean loginFormBean,
    			final ModelMap modelMap) {
    	String resultPage = "someOtherPage";
    		
    	final BindException errors = new BindException(loginFormBean, "loginFormBean");
    	formValidator.validate(loginFormBean, errors);		
    	if(errors.hasErrors()) {
    	    resultPage = "loginPage";
    	}
    	return resultPage;
        }
    }
    JSP Page
    Code:
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags/form" %>
    
    <spring:form method="post" modelAttribute="loginFormBean">
       <span style="font-weight:bold; color: red">
          <spring:errors path="*" />
       </span><br />
    			
       <b>Username:</b><br>
       <spring:input path="username" id="username" size="25" maxlength="100" /><br/>
       <b>Password:</b><br/>
       <spring:password path="password" id="password" size="25" maxlength="100" /><br/><br/>
       <div style="float:right">
          <button id="submit">Sign In</button>
       </div>
    </spring:form>
    Spring Bean Configurations:

    webMvc-config.xml
    Code:
    <mvc:annotation-driven />
    <context:component-scan base-package="com.demo.web.controller" />
    <mvc:interceptors>
       <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" /> 
    </mvc:interceptors>
        
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
    
    <bean id="internalViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/views/"/>
       <property name="suffix" value=".jsp"/>
    </bean>
        
    <bean id="loginFormValidator" class="com.demo.web.validator.LoginFormValidator" />
    
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>file://Users/niranjan/my-config/app/messages/errorMessages</value>
            </list>
        </property>
        <property name="cacheSeconds" value="1" />
    </bean>
    web.xml
    Code:
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/wsApplicationContext.xml</param-value>
    </context-param>
    
    <listener>
        <description>Spring Application Context listener. This must be loaded first</description>
        <display-name>Spring Context Config Listener</display-name>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <servlet>
        <servlet-name>Spring Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                    classpath:spring/webMvc-config.xml
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>Spring Servlet</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

  • #2
    Should I assume that Spring MVC validation doesn't work? I do not want to use JSR 303 validation.

    My post is there for quite a few time and it seems no answer is available. It is really frustrating because Spring 3 MVC is highlighting this validation as ONE OF THE BEST FEATURES.

    The entire documentation seems to be theory with least practical usage. There is not a single complete sample application available with these kind of things.

    Hope Springsource is listening. Please Mr. Ron, ask your guys to provide sample applications other than this pile of theories.

    Thanks,
    Niranjan

    Comment


    • #3
      You're not putting the validation results in the model map fed to your view. As a result, there is no validation context to render. You need to call errors.getModel() and put that result in the ModelMap.

      Keith

      Comment


      • #4
        J2EE Developer

        I think, it will be easier to put @Valid annotation in Controller method like this:

        public String handleLogin(@Valid @ModelAttribute("loginFormBean") final LoginFormBean loginFormBean,
        BindingResult result) {

        But final ModelMap modelMap I replaced with BindingResult result
        In my code it works fine
        Last edited by jczupryn; Feb 11th, 2011, 02:32 AM.

        Comment

        Working...
        X