3

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

我这样做了,但是 result.hasErrors() 总是返回 null 并且我的控件正在移动到成功页面。

登录.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(我的 pojo)

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

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

4

2 回答 2

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);
   }
}
于 2013-05-23T15:15:41.683 回答
0

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

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

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

除此之外,在我看来一切都很好。

于 2013-10-11T18:55:01.710 回答