web.xml的代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 加载spring配置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 这是加载springmvc的配置 -->
<!-- spring自带的解决乱码的过滤器 -->
<filter>
<filter-name>utf</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>utf</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<!-- 配置这个selevlet来加载sprinmvc的配置文件 -->
<filter-name>hidden</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hidden</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 通过这个参数去找配置文件 不加这个参数默认在 /WEB-INF/找spservlet-name-servlet.xml这个文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/springmvc.xml</param-value>
</init-param>
<!-- 启动tomcat的时候就加载 -->
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- /拦截所有以.action -->
<url-pattern>*.action</url-pattern>
<!-- /拦截所有servlet -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
">
<!-- 加载消息源 因为是spring的所以只能写在spring的配置文件中-->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- 把消息国际化的basename注入进来 -->
<property name="basename" value="classpath:/my"></property>
</bean>
</beans>
springmvc 的配置文件
<?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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
">
<!-- 配置扫描 -->
<context:component-scan base-package="cn.et"></context:component-scan>
<!-- 通过这个类加载spring消息源才能在实体类中用消息国际化 (验证器) -->
<bean id="myMessage" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 把spring的消息源注入进来 -->
<property name="validationMessageSource" ref="messageSource"></property>
</bean>
<!--告诉tomcat用这个验证器 -->
<mvc:annotation-driven validator="myMessage">
</mvc:annotation-driven>
</beans>
action的代码
验证消息同时处理多个对象BindingResult跟在对象后面即可。
Errors是BindingResult的父接口,效果一样,只是不能new FieldError();
@Controller
@RequestMapping("/day0602")
public class VaildatorAction{
@Autowired
private MessageSource source;
/**
* 必须要添加@Valid注解,不加不会进行声明式验证
*
* 当@valid注解标示的实体类验证失败后
* 所有的错误消息都被注入到BindingResult对象中
*
* 在显示错误时springmvc标签的path由对象名(类名的第一个字母小写).属性名
*
* @ModelAttribute("user")可以修改对象名
*
* @param user
* @return
*/
@RequestMapping("/vaildator.action")
//@ModelAttribute("user")可以通过这个改名字默认首字母小写 还会传到jsp界面 request BindingResult是注入错误消息的对象
public String vaildator(@ModelAttribute("user") @Valid UserinfoEntity user,BindingResult bindingResult,Locale locale,HttpServletRequest request){
//代码验证 验证密码与在此输入密码
if(!user.getPassword().equals(user.getRepassword())){
//获取国际化的消息
String str=source.getMessage("notpassword", null,locale);
//注入到错误消息对象
bindingResult.addError(new FieldError("repassword", null, str));
}
//验证不通过返回
if(bindingResult.hasErrors()){
return "/day20170602/vaildator.jsp";
}
request.setAttribute("birthday",new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()));
return "/day20170602/suc.jsp";
}
}
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint
使用hibernate validator出现上面的错误, 需要 注意
@NotNull 和 @NotEmpty 和@NotBlank 区别
@NotEmpty 用在集合类上面
@NotBlank 用在String上面
@NotNull 用在基本类型上
如果在基本类型上面用NotEmpty或者NotBlank 会出现上面的错
public class UserinfoEntity {
@NotBlank(message="{notEmpty}")
private String userName;
@NotBlank(message="{notEmpty}")
private String password;
@NotBlank(message="{notEmpty}")
private String repassword;
@NotBlank(message="{notEmpty}")
private String location;
@NotNull(message="{notEmpty}")
@DateTimeFormat(pattern="yyyy-MM-dd")
@Past(message="{dates}")
private Date birthday;
@NotBlank(message="{notEmpty}")
@Email(message="{emailnot}")
private String email;
@NotBlank(message="{notEmpty}")
@Pattern(regexp="^[0-9]{17}([0-9]|x|X)$",message="{cidnot}")
private String userid;
@NotBlank(message="{notEmpty}")
@Pattern(regexp="^[0-9]{11}",message="{phonenot}")
private String phone;
@URL(message="{urls}")
@NotBlank(message="{notEmpty}")
private String url;
public String getRepassword() {
return repassword;
}
jsp的代码
把jsp界面日期类型转换成字符串
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<fmt:formatDate value="${user.birthday }" pattern="yyyy-MM-dd HH:mm:ss"/>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="t"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/day0602/vaildator.action" method="post">
<t:message code="userName"></t:message><input type="text" name="userName"/>
<font color="red"><form:errors path="user.userName"></form:errors></font><br/>
<t:message code="password"></t:message><input type="password" name="password"/>
<font color="red"><form:errors path="user.password"></form:errors></font><br/>
<t:message code="agpassword"></t:message><input type="password" name="repassword"/>
<font color="red"><form:errors path="user.repassword"></form:errors></font><br/>
<t:message code="sex"></t:message><input type="radio" name="sex" value="0" checked/>
<t:message code="man"></t:message><input type="radio" name="sex" value="1" />
<t:message code="woman"></t:message><br/>
<t:message code="birthday"></t:message><input type="text" name="birthday"/>
<font color="red"><form:errors path="user.birthday"></form:errors></font><br/>
<t:message code="location"></t:message><input type="text" name="location"/>
<font color="red"><form:errors path="user.location"></form:errors></font><br/>
<t:message code="phone"></t:message><input type="text" name="phone"/>
<font color="red"><form:errors path="user.phone"></form:errors></font><br/>
<t:message code="userid"></t:message><input type="text" name="userid"/>
<font color="red"><form:errors path="user.userid"></form:errors></font><br/>
<t:message code="email"></t:message><input type="text" name="email"/>
<font color="red"><form:errors path="user.email"></form:errors></font><br/>
<t:message code="url"></t:message><input type="text" name="url"/>
<font color="red"><form:errors path="user.url"></form:errors></font><br/>
<input type="submit" value="<t:message code="submit"></t:message>"/><br/>
</form>
</body>
</html>
Spring的org.springframework.validation是校验框架所在的包
<mvc:annotation-driven/>会默认装配好一个LocalValidatorFactoryBean,通过在处理方法的入参上标注@Valid注解即可让Spring MVC在完成数据绑定后执行数据校验的工作。
@Null 被注释的元素必须为 null
@NotNull 被注释的元素必须不为 null
@AssertTrue 被注释的元素必须为 true
@AssertFalse 被注释的元素必须为 false
@Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
@DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
@Size(max, min) 被注释的元素的大小必须在指定的范围内
@Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
@Past 被注释的元素必须是一个过去的日期
@Future 被注释的元素必须是一个将来的日期
hibernate-validator-4.3.2.Final架包的下载地址:
https://sourceforge.net/projects/hibernate/?source=typ_redirect
必需导入的四个包:
hibernate-validator-4.3.2.Final.jar
hibernate-validator-annotation-processor-4.3.2.Final.jar
jboss-logging-3.1.0.CR2.jar
validation-api-1.0.0.GA.jar