springmvc服务端数据验证
网上有很多好的文章,本人主要是参照了开涛的博客做的验证,这里谈一下个人的具体使用,和一些在他的博客中没讲到的具体问题的处理。
用的是基于jsr-303验证框架做的声明式服务端数据验证。至于编程式,我就不讲了,我也没用到,不过声明式有时候不能完全满足要求,在这时可能也需要结合编程式验证。
简单说一下如何我是使用的:
1.需要的jar包:hibernate-validator-4.3.0.Final.jar,validation-api-1.0.0.GA.jar,(jboss-logging-3.1.0.CR2.jar这个好象不需要)
2.配置:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-autowire="byName" >
<import resource="classpath:/spring/propertyFileConfigurer.xml" />
<!-- 自动搜索@Controller标注的类 -->
<context:component-scan base-package="com.**.web"/>
<!-- <mvc:annotation-driven /> -->
<bean id="tplViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/tpl/"/>
<property name="viewNames">
<list>
<value>*.html</value>
</list>
</property>
<property name="order" value="1"/>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/pages/${mc.viewResolver.basename}/"/>
<property name="suffix" value=".jsp"/>
<property name="order" value="2"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer" ref="webBindingInitializer"/>
</bean>
<bean id="mappingJacksonJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />
</property>
</bean>
<bean id="webBindingInitializer" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="conversionService" ref="conversionService"/>
<property name="validator" ref="validator"/>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
<!-- 如果不加默认,则使用classpath下的 ValidationMessages.properties -->
<!-- <property name="validationMessageSource" ref="messageSource"/> -->
</bean>
<!-- ①注册ConversionService -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
</list>
</property>
</bean>
3.写验证类:这是用于个人注册时的验证类
public class UsersRegValidator implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
//columns START
private String loginName;
private String password;
private String email;
private String mobile;
private String nickname;
public void setLoginName(String value) {
this.loginName = value;
}
@NotEmpty(message="{loginName.not.empty}")
@Length(min = 4, max = 12, message = "{loginName.length}")
@Pattern(regexp = Constants.REGEXP_CODE, message = "${formatter.loginName}")
@LoginNameOnly
public String getLoginName() {
return this.loginName;
}
public void setPassword(String value) {
this.password = value;
}
@NotEmpty(message="{password.not.empty}")
@Length(min = 5, max = 12, message = "{password.length}")
public String getPassword() {
return this.password;
}
public void setEmail(String value) {
this.email = value;
}
@NotEmpty(message="{email.not.empty}")
@Length(min = 1, max = 60, message = "{email.length}")
@Email(message="{formatter.email}")
@EmailOnly
public String getEmail() {
return this.email;
}
public void setMobile(String value) {
this.mobile = value;
}
@NotEmpty(message="{mobile.not.empty}")
@Pattern(regexp = Constants.REGEXP_MOBILE, message = "${formatter.mobile}")
public String getMobile() {
return this.mobile;
}
public void setNickname(String value) {
this.nickname = value;
}
@NotEmpty(message="{nickname.not.empty}")
@Length(min = 2, max = 10, message = "{nickname.length}")
@Pattern(regexp = Constants.REGEXP_SPECIALCHARACTER, message = "${validate.specialCharacter}")
public String getNickname() {
return this.nickname;
}
}
4.在controller中 使用进行服务端验证
/**
* 个人注册.--注册
**/
@RequestMapping
public String saveRegInfo(@Valid @ModelAttribute("frontValidate") final UsersRegValidator frontValidate, Errors errors,final Users users) throws Exception {
if(errors.hasErrors()) {
return "admin/validate";
}
return "";
}
5.显示验证结果的界面:这里显示结果的界面不是注册的界面,是单独的一个通用界面,
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="/commons/meta_error.jsp"%>
<html>
<head>
<title>Error Page</title>
</head>
<body>
<div class="wrap" id="frontContent" >
<!--header-->
<jsp:include page="/pages/guanlin/guanlincommon/header.jsp" flush="true">
<jsp:param name="modelname" value="数据验证失败" />
</jsp:include>
<!--header End-->
<div class="main">
<h3>对不起,数据验证失败</h3>
<form:form commandName="frontValidate">
<form:errors path="*" cssStyle="color:red"></form:errors><br/>
</form:form>
<br/>
<input id="subBtn" type="button" οnclick="history.back();" value="返回"/>
<br/><br/>
</div>
</div>
</body>
</html>
到此,服务端验证就结束了。其实很简单。