带有注释的Spring MVC中的自定义验证器不起作用

时间:2013-05-23 12:18:39

标签: spring-mvc validation customvalidator

您好我是spring mvc验证框架的新手。我正在尝试为登录表单实现一个简单的自定义验证器。

我这样做了,但是result.hasErrors()总是返回null,我的控制权正转移到成功页面。

的Login.jsp

<form:form method="POST" action="/SampleWeb/logins" commandName="USER">

<table align="center" border="5" bordercolor="orange">
<tr>
    <td style="color: white" align="center"><label>User Name</label></td>
    <td><input name="userName" /></td>
</tr>
<tr>
    <td style="color: white" align="center"><label>Password</label></td>
    <td><input name="password" type="password"/></td>
</tr>
<tr>
    <td colspan="2" style="color: white" align="center">        
         <input type="submit" value="Submit"/>
    </td>
</tr>
</table>
<h3 align="center" style="color: red">${error}</h3>     
</form:form>

采样servlet.xml中

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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:annotation-config />   
    <mvc:annotation-driven />

   <context:component-scan base-package="com.sample.web.controller" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>

    </bean> 

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
      <property name="basename" value="/WEB-INF/messages"/>
    </bean> 

</beans>

UserValidator(我的自定义验证器)

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

@Component
public class UsersValidator implements Validator {

  @Override
  public boolean supports(Class<?> clazz) {
    return clazz.isAssignableFrom(users.class);
  }
  @Override
  public void validate(Object obj, Errors errors) {
    users user = (users) obj;
    String userName = user.getUserName();
    validateuserName(userName, errors);
  }
  private void validateuserName(String userName, Errors errors) {

    if (isValidString(userName) && isNotBirminghamuserName(userName)) {
      errors.rejectValue("userName", "UsersValidator.userName.notBirmingham",
          "Not a b group user ");
    }
  }
  private boolean isValidString(String str) {
    return isNotNull(str) && (str.length() > 0);
  }
  private boolean isNotNull(String userName) {
    return userName != null;
  }
  /** The first character of the Birmingham post code is 'B' */
  private boolean isNotBirminghamuserName(String userName) {
    char val = userName.charAt(0);
    return val != 'B';
  }
}

控制器

import javax.validation.Valid;

@Controller
public class LoginController {
    @Autowired
    private UsersValidator usersValidator;

   final RequestHandler  requestHandler = new RequestHandler();
   @RequestMapping(value = "/login", method = RequestMethod.GET)
   public ModelAndView login() {
      return new ModelAndView("login", "users", new users());
   }

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

   @RequestMapping(value = "/logins",method = RequestMethod.POST)
   public ModelAndView validateUser(@Valid users user, BindingResult result,@ModelAttribute("USER")users users,RedirectAttributes redirectAttributes,ModelMap model) {

       if (result.hasErrors()) {
              model.addAttribute("error",
                  "No Errors This Time for postal code: " + user.getUserName());
            }
            return new ModelAndView("sample", model);
       }
}

Users.java(my pojo)

public class users implements Serializable {
    private String userName;
    private String password;        
    //getter setters    
}

我的意思是跳过验证器类中的验证,控件直接转到成功页面。 有人可以在这个问题上帮助我吗?

2 个答案:

答案 0 :(得分:0)

尝试重构您的validateUser方法,以便获得验证的modelAttribute。

@RequestMapping(value = "/logins",method = RequestMethod.POST)
public ModelAndView validateUser(@ModelAttribute("USER") @Valid users users, BindingResult result, RedirectAttributes redirectAttributes, ModelMap model) {

   if (result.hasErrors()) {
      model.addAttribute("error",
          "No Errors This Time for postal code: " + user.getUserName());
    }
    return new ModelAndView("sample", model);
   }
}

答案 1 :(得分:0)

除了Will Keeling在控制器中清理参数的答案之外,请尝试在modelAttribute="users"标记而不是form:form中使用commandName="USER"

来源:http://codetutr.com/2013/05/28/spring-mvc-form-validation/

我还建议以大写和单数形式命名您的POJO:User而不是users,因为该类的每个实例都是个人用户。

除此之外,对我来说一切都很好。