public interface Formatter<T>这里的 T 表示由字符串转换的目标数据类型。该接口有 parse 和 print 两个接口方法,自定义格式化转换器类必须覆盖它们。
public T parse(String s, java.util.Locale locale) public String print(T object, java.util.Locale locale)parse 方法的功能是利用指定的 Locale 将一个 String 类型转换成目标类型,print 方法与之相反,用于返回目标对象的字符串表示。
package net.biancheng.po; import java.util.Date; public class User { private String name; private Integer age; private Double height; private Date createDate; /**省略setter和getter方法*/ }
package net.biancheng.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import net.biancheng.po.User; @Controller public class FormatterController { @RequestMapping("/formatter") public String myFormatter(User us, Model model) { model.addAttribute("user", us); return "showUser"; } }
package net.biancheng.formatter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import org.springframework.format.Formatter; import org.springframework.stereotype.Component; @Component public class MyFormatter implements Formatter<Date> { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); public String print(Date object, Locale arg1) { return dateFormat.format(object); } public Date parse(String source, Locale arg1) throws ParseException { return dateFormat.parse(source); // Formatter只能对字符串转换 } }
<!--注册MyFormatter --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="formatters"> <set> <bean class="net.biancheng.formatter.MyFormatter" /> </set> </property> </bean> <mvc:annotation-driven conversion-service="conversionService" />
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>添加用户</title> </head> <body> <form action="${pageContext.request.contextPath}/formatter" method="post"> 用户名:<input type="text" name="name" /> <br> 年龄:<input type="text" name="age" /> <br> 身高:<input type="text" name="height" /> <br> 创建日期:<input type="text" name="createDate" /> <br> <input type="submit" value="提交" /> </form> </body> </html>创建信息显示页面 showUser.jsp,代码如下。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>用户信息</title> </head> <body> 您创建的用户信息如下: <br /> <!-- 使用EL表达式取出model中的user信息 --> 用户名:${user.name } <br /> 年龄:${user.age } <br /> 身高:${user.height } <br /> 创建日期:${user.createDate } </body> </html>
addUser.jsp
showUser.jsp
本文链接:http://task.lmcjl.com/news/15684.html