Spring总是试图用默认的语言区域将日期输入绑定 到java.util.Date。假如想让Spring使用不同的日期样 式,就需要用一个Converter(转换器)或者 Formatter(格式化)来协助Spring完成。
利用Converter进行日期的格式化
Spring的Converter是一个可以将一种类型转换成另 一种类型的对象。例如,用户输入的日期可能有许多种 形式,如“December 25,2014”“12/25/2014”“2014-12- 25” ,这些都表示同一个日期。默认情况下,Spring会 期待用户输入的日期样式与当前语言区域的日期样式相 同。例如,对于美国的用户而言,就是月/日/年格式。 如果希望Spring在将输入的日期字符串绑定到Date时, 使用不同的日期样式,则需要编写一个Converter,才能 将字符串转换成日期。
需要实现org.springframework.core.convert.converter.Converter的接口
public interface Converter<S, T
例如
package converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.core.convert.converter.Converter; //必须实现 Converter public class StringToDateConverter implements Converter<String, Date> { private String datePattern; public StringToDateConverter(String datePattern) { this.datePattern = datePattern; System.out.println("instantiating .... converter with pattern:*" + datePattern); } // 转换日期格式
@Override public Date convert(String s) { try { SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern); dateFormat.setLenient(false); return dateFormat.parse(s); } catch (ParseException e) { // the error message will be displayed when using // <form:errors> throw new IllegalArgumentException("invalid date format. Please use this pattern\"" + datePattern + "\""); } } }
2. springmvc-cofing.xml配置
<mvc:annotation-driven conversion-service="conversionService"/> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="converter.StringToDateConverter"> <constructor-arg type="java.lang.String" value="MM-dd-yyyy" /> </bean> </list> </property> </bean>
package controller; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import domain.Employee; @org.springframework.stereotype.Controller public class EmployeeController { private static final Log logger = LogFactory.getLog(EmployeeController.class); @RequestMapping(value="employee_input") public String inputEmployee(Model model) { model.addAttribute(new Employee()); return "EmployeeForm"; } @RequestMapping(value="employee_save") public String saveEmployee(@ModelAttribute Employee employee,BindingResult bindingResult,Model model) { if(bindingResult.hasErrors()) { FieldError fieldError = bindingResult.getFieldError(); logger.info("Code:" + fieldError.getCode() + ", field:" + fieldError.getField()); } // save employee here model.addAttribute("employee",employee); return "EmployeeDetails"; } }
4.view视图
<%@ taglib prefix="form" uri="http://www.springframework.org/ta gs/form" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" % > <!DOCTYPE html> <html> <head> <title>Add Employee Form</title> <style type="text/css">@import url("<c:url value="/css/main.css"/>");</style> </head> <body> <div id="global"> <form:form commandName="employee" action="employee_save" method ="post"> <fieldset> <legend>Add an employee</legend> <p> <label for="firstName">First Name: </label> <form:input path="firstName" tabindex="1"/> </p> <p> <label for="lastName">First Name: </label> <form:input path="lastName" tabindex="2"/> </p> <p>
<!-- 打印错误 -->
<form:errors path="birthDate" cssClass="error"/> </p> <p> <label for="birthDate">Date Of Birth: </label> <form:input path="birthDate" tabindex="3" /> </p> <p id="buttons"> <input id="reset" type="reset" tabindex="4"> <input id="submit" type="submit" tabindex="5" value="Add Employee"> </p> </fieldset> </form:form> </div> </body> </html>
原文:https://www.cnblogs.com/jiangfeilong/p/10806361.html