springmvc4的validation配置

有两种配置,一种是继承一个验证类,一种是注解,这里主要讲注解。

同时注解方式也可细分,一种是将提示信息硬编码到代码里,这种配置简单,另外一种稍微麻烦点,但可以把错误提示信息写到配置文件里。

首先上pom

<!-- 注解规范javax及验证 -->
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.2.2.Final</version>
		</dependency>

接着页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="sf" %> 
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table>
		<sf:form method="post"  action="add" modelAttribute="testVo">
			<fieldset>
				<tr>
					<td><sf:label path="name">姓名</sf:label></td>
					<td><sf:input path="name"/><br/>
						<sf:errors path="name"></sf:errors>
					</td>
				</tr>				
				<tr>
					<td><sf:label path="age">年龄</sf:label></td>
					<td><sf:input path="age"/><br/>
						<sf:errors path="age"></sf:errors>
					</td>
				</tr>				
				<tr>
					<td><input type="submit" value="submit"/> </td>
					<td><input type="reset" value="reset"/>
					</td>
				</tr>				
			</fieldset>
		</sf:form>
	</table>
</body>
</html>

然后controller

/**
 * <p>Description: </p>
 * @author scc
 * @since 创建时间:2015年11月3日 上午10:18:15
 */
@Controller
public class HomeController {
	@Value("#{testDao}")
	private ITestDao iTestDao;
	@RequestMapping("/home")
	public String test1(Model model){
		model.addAttribute("testVo", new TestVO());
		return "index";
	}
	@RequestMapping("/add")
	public String test2(@Valid @ModelAttribute("testVo") TestVO	testVo,BindingResult result){
		if(result.hasErrors()) {
			return "index";
		} else {			
			iTestDao.add(testVo);
			return "index";
		}
	}
}

还有TestVo

/**
 * <p>Description: </p>
 * @author scc
 * @since 创建时间:2015年11月3日 上午11:15:31
 */
public class TestVO {
	@Size(min=3,max=5,message="{testvo.name}")
	private String name;
	@NotNull(message="{testvo.age}")
	private Integer age;
	/* 省略setter和getter */
}

注意message这个属性,如果要硬编码提示信息,那么到此就配置完毕,在message里写上提示信息即可,若使用另外一种,则继续往下看,在springmvc的配置文件里

 <!-- spring mvc验证开始 ,若不使用这种配置,需要将错误信息硬编码到代码里,不易修改-->
    <!-- 默认的注解映射的支持 -->  
    <mvc:annotation-driven validator="validator" conversion-service="conversion-service" />
    
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass"  value="org.hibernate.validator.HibernateValidator"/>
        <!--不设置则默认为classpath下的 ValidationMessages.properties -->
        <property name="validationMessageSource" ref="validatemessageSource"/>
    </bean>
    <bean id="conversion-service" class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
    <bean id="validatemessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
        <property name="basename" value="classpath:validatemessages"/>  
        <property name="fileEncodings" value="utf-8"/>  
        <property name="cacheSeconds" value="120"/>  
    </bean>
    <!-- spring mvc验证结束 -->

同时在classpath下建立validatemessages.properties,编码一定是utf-8

若有中文,先在别的文档里写好,再粘贴进去,自动转成unicode编码。同时在配置文件里也可以用{}获取一些简单的属性,比如min、max,

testvo.name={min}\u54C8{max}\u54C8haha
testvo.age=heihei

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值