类型转换
index页面:
<body> <s:form action="dateConvert.action"> <div class="infos"> <table class="field"> <tr> <td class="field">请输入日期:</td> <td><input type="text" class="text" name="timeDate" /></td> </tr> <s:fielderror /> </table> <div class="buttons"> <s:submit value="转换格式"/> </div> </div> </s:form> </body>
success页面:
<body> <s:property value="timeDate"/> <br> </body>
实体类DateConvertAction:
public class DateConvertAction extends ActionSupport { private Date timeDate; public String execute(){ return SUCCESS; } public Date getTimeDate() { return timeDate; } public void setTimeDate(Date timeDate) { this.timeDate = timeDate; } }
自定义转换器:
public class DateConverter extends StrutsTypeConverter { // 支持转换的多种日期格式,可增加时间格式 private final DateFormat[] dfs = { new SimpleDateFormat("yyyy 年MM 月dd 日"), new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("MM/dd/yy"), new SimpleDateFormat("yyyy.MM.dd"), new SimpleDateFormat("yyMMdd"), new SimpleDateFormat("yyyy/MM/dd") }; /** * 将指定格式字符串转换为日期类型。 */ public Object convertFromString(Map context, String[] values, Class toType) { String dateStr = values[0];// 获取日期的字符串 for (int i = 0; i < dfs.length; i++) {// 遍历日期支持格式,进行转换 try { return dfs[i].parse(dateStr); } catch (Exception e) { continue; } } throw new TypeConversionException("转换错误"); } public String convertToString(Map context, Object object) { Date date = (Date) object; // 输出的格式是yyyy-MM-dd return new SimpleDateFormat("yyyy-MM-dd").format(date); } }
配置struts.xml配置文件:
<struts> <constant name="struts.custom.i18n.resources" value="message"/> <constant name="struts.i18n.encoding" value="UTF-8"/> <constant name="struts.ui.theme" value="simple"/> <package name="renthouse" extends="struts-default"> <default-action-ref name="defaultAction" /> <action name="dateConvert" class="cn.jbit.action.DateConvertAction"> <result name="input">index.jsp</result> <result name="success">success.jsp</result> </action> </package> </struts>
创建一个名为xwork-conversion.properties的文本配置全局类型转换:
java.util.Date=cn.jbit.util.DateConverter