34、(知识篇)SpringMVC11 JSR303 使用 / Spring表单 /错误信息国际化

/**
* JSR303 使用 / Spring表单 /错误信息国际化

* JSR303
* 1、添加Hibernate-validtor相关jar包
* 可以到官网下载,并且加入其中required文件夹的jar包
* 2、在需要验证的pojo中加入如
* @NotNull 非空
* @Min 最小值 等的注解
* 3、在SpringMVC中需要验证的类上面加上@Valid 标签标识为需要验证
* 4、使用BindingResult/Errors获取错误信息

* ==========================================================

* Spring表单
* 1、表单使用标签:<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
* 2、form使用 <form:form action="testJSR" method="POST" modelAttribute="stu" ></form>
*  其中,modelAttribute 默认正为 command, 可以在controller中指定,如果找不到则会报错
* 3、其余与平常表单使用类似

* ===========================================================

* JSR303错误信息国际化
* 方法一 
* 在对应字段写上限制:@Min(value=20)
* 在classpath中建立国际化文件
* 在springmvc.xml中 配置国际化文件 
* <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="i18N"></property>
</bean>
即可实现错误信息的自定义国际化

* 方法二
* 在验证条件加上自定义文字:@Min(value=20,message="你小于20岁了!")
*
* 方法三
* 在ClassPath中建立ValidationMessages.properties(名字一定要是ValidationMessages)
* 用以下形式 制定message的key为properties中的值 @Min(value=20,message="{min.student.age2}")



* 附录:
*  JSR303常用注解:
*  JSR 303中含有的注解
@Null   被注释的元素必须为 null  
@NotNull    被注释的元素必须不为 null  
@AssertTrue     被注释的元素必须为 true  
@AssertFalse    被注释的元素必须为 false  
@Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值  
@Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值  
@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值  
@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值  
@Size(max=, min=)   被注释的元素的大小必须在指定的范围内  
@Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内  
@Past   被注释的元素必须是一个过去的日期  
@Future     被注释的元素必须是一个将来的日期  
@Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式  
------------------------------  
Hibernate Validator 附加的注解
@NotBlank(message =)   验证字符串非null,且长度必须大于0  
@Email  被注释的元素必须是电子邮箱地址  
@Length(min=,max=)  被注释的字符串的大小必须在指定的范围内  
@NotEmpty   被注释的字符串的必须非空  
@Range(min=,max=,message=)  被注释的元素必须在合适的范围内 

* /


测试类:

package com.spring.test;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {

	/**
	 * JSR303 使用 / Spring表单 /错误信息国际化
	 * 
	 * JSR303
	 * 1、添加Hibernate-validtor相关jar包
	 * 可以到官网下载,并且加入其中required文件夹的jar包
	 * 2、在需要验证的pojo中加入如
	 * @NotNull 非空
	 * @Min 最小值 等的注解
	 * 3、在SpringMVC中需要验证的类上面加上@Valid 标签标识为需要验证
	 * 4、使用BindingResult/Errors获取错误信息
	 * 
	 * ==========================================================
	 * 
	 * Spring表单
	 * 1、表单使用标签:<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
	 * 2、form使用 <form:form action="testJSR" method="POST" modelAttribute="stu" ></form>
	 * 	  其中,modelAttribute 默认正为 command, 可以在controller中指定,如果找不到则会报错
	 * 3、其余与平常表单使用类似
	 * 
	 * ===========================================================
	 * 
	 * JSR303错误信息国际化
	 * 方法一 
	 * 		在对应字段写上限制:@Min(value=20)
	 * 		在classpath中建立国际化文件
	 * 		在springmvc.xml中 配置国际化文件 
	 * 		<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
				<property name="basename" value="i18N"></property>
			</bean>
			即可实现错误信息的自定义国际化
			
	 *	方法二
	 *		在验证条件加上自定义文字:@Min(value=20,message="你小于20岁了!")
	 *	
	 *	方法三
	 *		在ClassPath中建立ValidationMessages.properties(名字一定要是ValidationMessages)
	 *		用以下形式 制定message的key为properties中的值 @Min(value=20,message="{min.student.age2}")
	 * 
	 * 
	 * 
	 * 附录:
	 *  JSR303常用注解:
	 *  JSR 303中含有的注解
		@Null   被注释的元素必须为 null  
		@NotNull    被注释的元素必须不为 null  
		@AssertTrue     被注释的元素必须为 true  
		@AssertFalse    被注释的元素必须为 false  
		@Min(value)     被注释的元素必须是一个数字,其值必须大于等于指定的最小值  
		@Max(value)     被注释的元素必须是一个数字,其值必须小于等于指定的最大值  
		@DecimalMin(value)  被注释的元素必须是一个数字,其值必须大于等于指定的最小值  
		@DecimalMax(value)  被注释的元素必须是一个数字,其值必须小于等于指定的最大值  
		@Size(max=, min=)   被注释的元素的大小必须在指定的范围内  
		@Digits (integer, fraction)     被注释的元素必须是一个数字,其值必须在可接受的范围内  
		@Past   被注释的元素必须是一个过去的日期  
		@Future     被注释的元素必须是一个将来的日期  
		@Pattern(regex=,flag=)  被注释的元素必须符合指定的正则表达式  
		------------------------------  
		Hibernate Validator 附加的注解
		@NotBlank(message =)   验证字符串非null,且长度必须大于0  
		@Email  被注释的元素必须是电子邮箱地址  
		@Length(min=,max=)  被注释的字符串的大小必须在指定的范围内  
		@NotEmpty   被注释的字符串的必须非空  
		@Range(min=,max=,message=)  被注释的元素必须在合适的范围内 
	 * 
	 * 
	 * @param stu
	 * @param result
	 * @return
	 */
	@RequestMapping("testJSR")
	public String testJSR(@Valid Student stu,BindingResult result,Map<String,Object> param) {
		System.out.println(stu);
		
		List<ObjectError> errors = result.getAllErrors();
		for (ObjectError error : errors) {
			System.out.println("error == "+error);
			param.put("msg", error.getDefaultMessage());
		}
		
		return "index";
	}
	
	
	@ModelAttribute
	public void setDefaultAttribute(Map<String,Object> param){
		System.out.println("Hello");
		param.put("stu", new Student());
	}

}

Student类:

package com.spring.test;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import org.springframework.stereotype.Component;


@Component
public class Student {
	@NotNull
	private String stuName;
	/*@Min(value=20,message="你小于20岁了!")*/
	/*@Min(value=20,message="{min.student.age2}")*/
	@Min(value=20)
	private int age;
	
	public Student() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Student(String stuName, int age) {
		super();
		this.stuName = stuName;
		this.age = age;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [stuName=" + stuName + ", age=" + age + "]";
	}
	
}

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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
	<context:component-scan base-package="com.spring.test"></context:component-scan>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="i18N"></property>
	</bean>
	
	
	<mvc:view-controller path="/index" view-name="index"/>
	<mvc:default-servlet-handler/>
	<mvc:annotation-driven></mvc:annotation-driven>
	
	
</beans>

i18N.properties

Min.student.age=the age must more than 20

i18N_zh_CN.properties

Min.student.age=\u5E74\u9F84\u4E0D\u80FD\u5C0F\u4E8E20\u5C81\u5462

ValidationMessages_zh_CN.properties

min.student.age2=\u5C0F\u4E8E20\u5C81\u4E0D\u80FD\u73A9


ValidationMessages.properties
min.student.age2=must more than 20


index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>
	HelloWorld!
	<br>
	${msg }
	<form:form action="testJSR" method="POST" modelAttribute="stu">
		姓名:<form:input path="stuName"/><form:errors path="stuName"></form:errors><br>
		年龄:<form:input path="age" /><form:errors path="age"></form:errors><br>
		<input type="submit" value="submit">
	</form:form>
	
	
</body>
</html>



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值