错误信息显示及全球化

1)每个属性在数据绑定和数据校验发生错误时,都会生成一个对应的FieldError对象

2)当属性校验失败后,校验框架会为该属性生成4个消息代码,

这些代码以校验注解类名为前缀,结合modleAttribute、属性名及属性类型名生成多个

对应的消息代码:例如User类中的password属性使用@Pattern注解,当该值不满足@Pattern所定义的规则时

产生以下4个错误代码

-Pattern.user.password

-Pattern.password

-Pattern.java.lang.String

-Pattern

3)当使用springmvc标签显示错误消息时,springmvc会查看web上下文是否装配对应国际化消息

如果没有,会显示默认错误消息,否则使用国际化

4)当数据类型转换或数据格式转换发生错误,或该有的参数不存在,或调用处理方法时发生错误,

都会在隐含模型中创建错误消息,错误代码前缀说明如下:

-required:参数必须,如@RequiredParam(“param1”)标注一个入参,但该参数不存在

-typeMismatch:数据绑定时,发生类型不匹配问题

-methodInvocation:调用处理方法时发生错误

注意:调用了Hibernate-validate验证,别忘注解@validate哦

	@RequestMapping(value={"/emp","/emp/add"}, method=RequestMethod.POST)
	private String add(@Valid Employee employee, BindingResult result,
			Map<String, Object> map){
		System.out.println(employee.toString());
		
		if(result.getErrorCount() > 0) {
			System.out.println("出错了");
			for(FieldError error : result.getFieldErrors()) {
				System.out.println(error.getField() + " : " + error.getDefaultMessage());
			}
			//若验证出错, 则转向定制的页面
			map.put("departments", departmentDao.getDepartments());
			return "input";
		}
		employeeDao.save(employee);
		return "redirect:/list";
	}

 i18n.properties国际化文件

Email.employee.email=邮箱格式不正确
Past.employee.birthday=日期过时
NotNull.employee.lastName=不能为空

typeMismatch.employee.birthday=日期转换错误

 要验证的bean

package com.hous.crud.bean;

import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;

import org.hibernate.validator.constraints.Email;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;

public class Employee {

	private Integer id;
	@NotNull
	private String lastName;

	@Email
	private String email;
	//1 male, 0 female
	private Integer gender;
	
	private Department department;
	
	@Past
	@DateTimeFormat(pattern="yyyy-MM-dd")
	private Date birthday;
	
	@NumberFormat(pattern="#,###,###.#")
	private Float salary;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Integer getGender() {
		return gender;
	}

	public void setGender(Integer gender) {
		this.gender = gender;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	
	public Float getSalary() {
		return salary;
	}

	public void setSalary(Float salary) {
		this.salary = salary;
	}

	public Employee(Integer id, String lastName, String email, Integer gender,
			Department department) {
		super();
		this.id = id;
		this.lastName = lastName;
		this.email = email;
		this.gender = gender;
		this.department = department;
	}

	public Employee() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @return the birthday
	 */
	public Date getBirthday() {
		return birthday;
	}

	/**
	 * @param birthday the birthday to set
	 */
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender
				+ ", department=" + department + ", birthday=" + birthday + ", salary=" + salary + "]";
	}

}

 springmvc.xml添加国际化配置

	<bean id="messageSource" 
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="i18n"></property>
	</bean>

 

<%@ page import="java.util.*"%>
<%@ 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"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加雇员信息</title>
</head>
<body>
<!-- 
1.why使用form标签
快速开发页面,方便表单值的回显 
2.注意
可以通过modelAttribute指定绑定的模型类型
若没有指定,则读取request的commond的表单bean
若该属性值也不存在则报错
-->

<form:form action="${pageContext.request.contextPath}/emp" method="POST" modelAttribute="employee">
<table>
	<form:errors path="*"/>
	<!-- id为整数类型 -->
	<c:if test="${employee.id == null }">
		<tr><th>First name</th><td><form:input path="lastName"/></td><td><form:errors path="lastName"/></td></tr>
	</c:if>
	<c:if test="${employee.id != null }">
		<form:hidden path="id"/>
		<input type="hidden" value="PUT" name="_method"/>
	</c:if>
	<tr><th>Email</th><td><form:input path="email"/></td><td><form:errors path="email"/></td></tr>
	<%
		Map<String, String> genders = new HashMap<String, String>();
		genders.put("0","Male");
		genders.put("1","Female");
		request.setAttribute("genders", genders);
	%>
	<tr><th>Gender</th><td><form:radiobuttons path="gender" items="${genders }"/></td></tr>
	<tr><th>Department</th><td><form:select path="department.id" items="${depts}"
		itemLabel="departmentName" itemValue="id" /></td></tr>
	<tr><th>birthday</th><td><form:input path="birthday"/></td><td><form:errors path="birthday"/></td></tr>
	<tr><th>salary</th><td><form:input path="salary"/></td><td><form:errors path="salary"/></td></tr>	
</table>
<input type="submit" value="提交"/>
</form:form>
</body>
</html>

 

猜你喜欢

转载自shuizhongyue.iteye.com/blog/2296497