< The bean ID = "messageSource" class = "org.springframework.context.support.ReloadableResourceBundleMessageSource" > < Property name = "BaseNames" value = "CLASSPATH: messages" /> <-! Encode the specified file -> < Property name = "fileencodings" value = "UTF8" /> <-! cache time of the resource file -> < Property name = "cacheSeconds" value = "120" /> </ the bean >
That the spring-web.xml above configuration, wherein, since the messages are placed in the resource file src folder, it is necessary to use as a positioning classpath.
package com.ual.web; import com.ual.model.Employee; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class EmployeeValidator implements Validator { @Override public boolean supports(Class<?> aClass) { return Employee.class.isAssignableFrom(aClass); } @Override public void validate(Object o, Errors errors) { Employee employee=(Employee)o; ValidationUtils.rejectIfEmpty(errors,"name","name.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors,"birthDate","birthDate.required"); } }
@Override public void validate(Object o, Errors errors) { Employee employee=(Employee)o; ValidationUtils.rejectIfEmpty(errors,"name","employee.name.required"); if(employee.getName()!=null&&employee.getName().equals("123")){ errors.rejectValue("name","employee.name.NotOne"); } ValidationUtils.rejectIfEmpty(errors,"birthDate","employee.birthDate.required"); }
These are custom validator.
View:
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <!DOCTYPE HTML> <html> <head> <title>Getting Started:Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> </head> <body> <div id="global"> <fieldset> <form:form commandName="employee" action="save-employee" method="post"> <legend> Add an employee</legend> <p> <form:errors path="name" /> </p> <p> <label >Name:</label> <form:input path="name" tabindex="1"/> </p> <p> <form:errors path="birthDate" cssClass="error"/> </p> <p> <label>BirthDate</label> <form:input path="birthDate" tabindex="2"/> </p> <p id="buttons"> <input id="reset" type="reset" tabindex="3"/> <input id="submit" type="submit" tabindex="4" value="AddEmployee"/> </p> </fieldset> </form:form> </div> </body> </html>
This code is based on dianzan project.