1

I am writing Web app in java using Spring Web MVC framework. Somehow validation does not work. Below is depicted the controller class:

@Controller
public class UserNameController 
{

    @InitBinder()
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new UserNameValidator());
    }

          // 
        @RequestMapping(value="userName.htm", method=RequestMethod.POST)
        public String doForm(@ModelAttribute("user") @Valid User user, BindingResult result, Model model) 
        {         
            System.out.println("------------ "+ user.getuName()+" ---------");
            if (result.hasErrors()) {
                System.out.print("===== errors ======");
            }

            model.addAttribute("user",user);
            return "registration";
        }


  public class UserNameValidator implements Validator 
  {
    public boolean supports(Class clazz) 
    { System.out.println("========== "+User.class.isAssignableFrom(clazz)+" ===================");
       return User.class.isAssignableFrom(clazz);    
    }

     public void validate(Object target, Errors errors)
     {
         System.out.println("=======================");
         User newUser = (User) target;
         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "uName", "field.required", "Required field");
         if(errors.hasFieldErrors("uName"))
         {
          //   if(user.existUser() == true)
            // {

             //}
             System.out.print("===== errors 2 ======");
         }

     }
  } 

}

Method 'supports' is invoked what gives true value, though 'validate' method stays idle. What is the problem?

<?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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"    
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

       <context:component-scan base-package="forum.web" />      


     <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />         

</beans>

User.java source file:

public class User
{

    private String uName;

    public User(){}

    public User(String uName)
    { System.out.println("=== Constructor==== " + uName);
        this.uName= uName;
    }
    public String toString()
    {System.out.println("=====toString()==== " + uName);
        return this.uName;
    }

    public String getuName()
    {
        return uName;
    }
    public void setuName(String uName)
    {
       this.uName = uName;  
    }
}

Main part of jsp page:

<form id="userName" action="userName.htm" method="post" accept="text/plain" accept-charset="UTF-8" enctype="application/x-www-form-urlencoded">

        <td>
        <label for> User Name: 
        </td> 
        <td> </td>
        <td> </td>
        <td>
            <form:errors path="uName"/>
        <input type="text" name="uName" maxlength="20" size="40" onmouseout="submitUName()" value="${user}"/> </p> </p>
        </td>
        <td>*</td>
        </form>       
    </tr> 

This is my updated Controller (new version):

@Controller
public class UserNameController 
{

   private Validator validator;

  public void setValidator(Validator validator)
   {
       this.validator= validator;
   }

    @InitBinder("user")
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new UserNameValidator());
        System.out.println("A binder for object: =============== " + binder.getObjectName());
    }

        @RequestMapping(value="userName.htm", method=RequestMethod.POST)
        public String userName(@ModelAttribute("user") User user, BindingResult result, Model model) 
        {         
            this.validator.validate(user, result);
            System.out.println("------------ "+ user.getuName()+" ---------");
            if (result.hasErrors()) {
                System.out.print("===== errors ======");
            }

            model.addAttribute("user",user);
            return "registration";
        }

  public class UserNameValidator implements Validator 
  {
    public boolean supports(Class clazz) 
    { System.out.println("========== "+User.class.isAssignableFrom(clazz)+" ===================");
       return User.class.isAssignableFrom(clazz);    
    }

     public void validate(Object target, Errors errors)
     {
         System.out.println("=======================");
         User newUser = (User) target;
         ValidationUtils.rejectIfEmptyOrWhitespace(errors, "uName", "field.required", "Required field");
         if(errors.hasFieldErrors("uName"))
         {
          //   if(user.existUser() == true)
            // {

             //}
             System.out.print("===== errors 2 ======");
         }

     }
  }

}

Though for some reasons this line this.validator.validate(user, result); causes NullPointerException. Anyway, 'validate' method is not invoked as above. Best regards

3
  • From the title alone I'm tempted to answer 'because the requirements keep changing" ;) Commented Jun 22, 2011 at 20:03
  • @jtoberon just edited the problem. Look above at the code, please. Commented Jun 22, 2011 at 22:03
  • Try making your form look more like the one in the Form Processing section of this page: infoq.com/articles/spring-2.5-ii-spring-mvc. I've always used Spring's form tag and specified its modelAttribute attribute. Commented Jun 22, 2011 at 22:09

1 Answer 1

2

Try specifying which object (model attribute or request parameter) the binder will be applied to, e.g. @InitBinder("user"). Note that you can provide an array of names.

Also, FYI you might be able to learn more about what's going on by doing this in your initBinder method: System.out.println("A binder for object: " + binder.getObjectName());

Another thing to check: that your JSP uses the same names as your controller. What does your tag look like? Does it have the modelAttribute="user" attribute set correctly?

Sign up to request clarification or add additional context in comments.

1 Comment

'code System.out.println("A binder for object: " + binder.getObjectName()); code' is giving me 'user'. I typed in user explicitly 'code @InitBinder("user"). code', but that does not help. @Bedwyr What do you mean 'requirements keep changing'? Who is changing requirements?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.