package com.domain; import java.io.Serializable; public class User implements Serializable { private String loginname; private String password; public String getLoginname() { return loginname; } public void setLoginname(String loginname) { this.loginname = loginname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.validator; import org.springframework.stereotype.Repository; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; import com.domain.User; @Repository("userValidator")//注解将该对象注释为Spring容器中的一个bean,名字为userValidator public class UserValidator implements Validator { /**该校验器能够对clazz类型的对象进行校验*/ @Override public boolean supports(Class<?> clazz) { // TODO Auto-generated method stub return User.class.isAssignableFrom(clazz); } /**对目标target进行校验,并将校验错误存到errors中*/ @Override public void validate(Object target, Errors errors) { // TODO Auto-generated method stub ValidationUtils.rejectIfEmpty(errors, "loginname", "loginnameError"); ValidationUtils.rejectIfEmpty(errors, "password", "passwordError"); User user = (User)target; if(user.getLoginname().length() > 10) { errors.rejectValue("loginname", null, "loginnameMax"); } if(user.getPassword() != null && user.getPassword().length() < 6) { errors.rejectValue("password", null, "passwordMin"); } } }
package com.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.domain.User; import com.validator.UserValidator; @Controller public class UserController{ //注入userValidator @Autowired @Qualifier("userValidator") private UserValidator userValidator; @RequestMapping(value="/login",method=RequestMethod.POST) public String login(@ModelAttribute User user,Model model,Errors errors) { model.addAttribute("user", user); //验证 userValidator.validate(user, errors); if(errors.hasErrors()) { return "loginForm"; } return "success"; } @RequestMapping(value="/{formName}") public String loginForm(@PathVariable String formName,Model model) { User user = new User(); model.addAttribute("user", user); return formName;//动态页面的跳转,可以是任何页面 } }
<context:component-scan base-package="com.controller"></context:component-scan> <context:component-scan base-package="com.validator"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/content/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <!-- 国际化 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <!-- 在web环境中一定要定位到classpath,放在src目录下--> <value>classpath:messages</value> </list> </property> <property name="useCodeAsDefaultMessage" value="false"/> <property name="defaultEncoding" value="UTF-8"/> <property name="cacheSeconds" value="60"/> </bean> <mvc:interceptors > <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean> </mvc:interceptors>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>测试Validation接口验证</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h3>登录页面</h3> <form:form modelAttribute="user" method="post" action="login"> <table> <tr> <td>登录名</td> <td><form:input path="loginname"/></td> <!-- 显示错误信息 --> <td><form:errors path="loginname" cssStyle="Color:red"></form:errors></td> </tr> <tr> <td>密码</td> <td><form:input path="password"/></td> <td><form:errors path="password" cssStyle="Color:red"></form:errors></td> </tr> <tr> <td><input type="submit" value="提交"/></td> </tr> </table> </form:form> </body> </html>
时间: 2024-10-10 21:11:45