标签:apn ecif 友情链接 fda arw roc spdy nav clu
这一章,我们开始struts2中自定义类型转换器的学习。
一、定义一个继承于StrutsTypeConverter的转换类:
package com.huhx.converter; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; public class DateConverter extends StrutsTypeConverter { private final DateFormat[] dateFormats = { new SimpleDateFormat("yyyy年MM月dd日"), new SimpleDateFormat("yyyyMM/dd") }; @Override public Object convertFromString(Map context, String[] values, Class toClass) { String dateStr = values[0]; for(int i = 0; i < dateFormats.length; i++) { try { return dateFormats[i].parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return null; } @Override public String convertToString(Map context, Object object) { Date date = (Date)object; return new SimpleDateFormat("yyyy-MM-dd").format(date); } }
二、在src下面定义一个properties文件,名为xwork-conversion.properties。struts2提供了两种方式来配置转换器
java.util.Date=com.huhx.converter.DateConverter
三、增加一个输入时间的jsp,名为converter.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>Insert title here</title> </head> <body> <form action="hello.action" method="post"> date: <input type="text" name="date"> <input type="submit" value="submit"> </form> </body> </html>
四、修改结果页的huhx.jsp为:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@taglib prefix="s" uri="/struts-tags" %> <!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> <h2>Hello huhx.</h2> date: <s:property value="date"/> </body> </html>
五、在Action中,接收date数据,增加以下内容:
private Date date; public Date getDate() { return date; } public void setDate(Date date) { this.date = date; }
六、运行效果如下:
标签:apn ecif 友情链接 fda arw roc spdy nav clu
原文地址:http://www.cnblogs.com/huhx/p/baseStruts3.html