1.springmvcValidator:
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>springmvc01</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 解决post提交乱码问题 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- spring mvc的前端控制器,类似struts2的核心过滤器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通过contextConfigLocation参数指定配置文件的位置,默认在WEB-INF/查找名称为 [servlet-name]-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- servlet随web容器而启动 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
springmvc.xml:
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注解扫描!!!--> <context:component-scan base-package="cn.zzsxt.controller"></context:component-scan> <!-- 配置视图解析器 --> <!-- InternalResourceViewResolver:支持JSP视图解析 --> <!-- viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar包; --> <!-- prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为: --> <!-- 前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,--> <!-- 则最终返回的jsp视图地址 "WEB-INF/view/hello.jsp" --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--文件上传视图解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--允许上传的文件最大大小 单位是byte--> <property name="maxUploadSize" value="100000000"></property> </bean> <!-- 注解映射器 说明 :对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配 ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!-- 注解适配器 说明:注解式处理器适配器,对标记@ResquestMapping的方法进行适配。 --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> <!-- springmvc使用<mvc:annotation-driven> --> <!-- 自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter, --> <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 --> <mvc:annotation-driven validator="validator"></mvc:annotation-driven> <!-- 处理静态资源 让静态资源可以直接访问--> <!-- <mvc:resources mapping="/jquery-ui-1.12.1.custom/**" location="/jquery-ui-1.12.1.custom/"/> --> <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 --> <mvc:default-servlet-handler/> <!-- 加载校验信息资源文件 --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <!-- 资源文件的基础名称 --> <property name="basenames"> <list> <value>classpath:CustomValidationMessages</value> </list> </property> <!-- 资源文件的编码集 --> <property name="fileEncodings" value="UTF-8"></property> <!-- 资源文件的缓存时间 --> <property name="cacheSeconds" value="120"></property> </bean> <!-- 校验器 --> <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property> <property name="validationMessageSource" ref="messageSource"></property> </bean> </beans>
CustomValidationMessages.properties:
username.length.error=u7528u6237u540Du957Fu5EA6u5FC5u987Bu57286u4F4Du523010u4F4Du4E4Bu95F4!
username.isnull.error=u7528u6237u540Du4E0Du80FDu4E3Au7A7A!
password.isnull.error=u5BC6u7801u4E0Du80FDu4E3Au7A7A!
UserController.java:
package cn.zzsxt.controller; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import cn.zzsxt.group.ValidationGroup1; import cn.zzsxt.group.ValidationGroup2; import cn.zzsxt.model.Userinfo; @Controller @RequestMapping("/user") public class UserController { @RequestMapping("/add") public String add(@Validated(value={ValidationGroup1.class}) Userinfo user,BindingResult result,Model model){ //判断是否存在错误消息 if(result.hasErrors()){ //获取所有错误消息 List<ObjectError> list = result.getAllErrors(); for (ObjectError objectError : list) { System.out.println("错误码:"+objectError.getCode()); System.out.println("错误消息:"+objectError.getDefaultMessage()); } model.addAttribute("errors", list); return "add"; } System.out.println("执行了add()方法...."); return "success"; } @RequestMapping("/login") public String login(@Validated(value={ValidationGroup2.class}) Userinfo user,BindingResult result,Model model){ //判断是否存在错误消息 if(result.hasErrors()){ //获取所有错误消息 List<ObjectError> list = result.getAllErrors(); for (ObjectError objectError : list) { System.out.println("错误码:"+objectError.getCode()); System.out.println("错误消息:"+objectError.getDefaultMessage()); } model.addAttribute("errors", list); return "add"; } System.out.println("执行了login()方法...."); return "success"; } }
ValidationGroup1.java:
package cn.zzsxt.group; public interface ValidationGroup1 { }
ValidationGroup2.java:
package cn.zzsxt.group; public interface ValidationGroup2 { }
Userinfo.java:
package cn.zzsxt.model; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; import cn.zzsxt.group.ValidationGroup1; import cn.zzsxt.group.ValidationGroup2; public class Userinfo { private int userId; @Size(min=6,max=10,message="{username.length.error}",groups={ValidationGroup1.class}) @NotEmpty(message="{username.isnull.error}",groups={ValidationGroup2.class}) private String userName; @NotEmpty(message="{password.isnull.error}") private String password; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
add.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% 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>My JSP 'index.jsp' starting page</title> </head> <body> <c:forEach items="${errors}" var="error"> ${error.defaultMessage}<br> </c:forEach> <hr> <form action="user/add" method="post"> 用户名:<input type="text" name="userName"/><br> 密码:<input type="text" name="password"/><br> <input type="submit" value="提交"/> </form> </body> </html>
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% 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>My JSP 'index.jsp' starting page</title> </head> <body> <c:forEach items="${errors}" var="error"> ${error.defaultMessage}<br> </c:forEach> <hr> <form action="user/login" method="post"> 用户名:<input type="text" name="userName"/><br> 密码:<input type="text" name="password"/><br> <input type="submit" value="提交"/> </form> </body> </html>