张玉龙 发表于 2013-2-6 11:07:49

structs 类型转换

date.jsp webroot/jsp<%@page contentType="text/html;charset=utf-8" pageEncoding="utf-8" %><%@taglib uri="/struts-tags" prefix="s"%><%@taglib uri="/struts-dojo-tags" prefix="sx" %><html> <head><sx:head/> </head><body> <s:property value="date"/> <s:form action="DateAction" namespace="/test">   <s:textfield name="date" title="yyyy-MM-dd HH:mm:ss"></s:textfield> <s:submit /> </s:form> </body> </html> web.xml<filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping>DateAction-conversion.propertiesdate =com.zyl.test.converter.DateConverterstruts.xml<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts> <package name="test"      namespace="/test"      extends="struts-default">       <action name="DateAction" class="com.zyl.servletapi.DateAction">      <result>/jsp/date.jsp</result>      <result name="input">/jsp/date.jsp</result>    </action></struts>    DateAction.javapackage com.zyl.servletapi;import java.util.Date;import com.opensymphony.xwork2.ActionSupport;public class DateAction extends ActionSupport {private Date date;public Date getDate() {return date;}public void setDate(Date date) {this.date = date;}public String execute(){return "success";}}DateConverter.javapackage com.zyl.test.converter;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Map;import org.apache.struts2.util.StrutsTypeConverter;public class DateConverter extends StrutsTypeConverter {private static String[] availableDateFormat = new String[] {"yyyy/MM/dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss" };private static SimpleDateFormat[] sdf = new SimpleDateFormat[] {new SimpleDateFormat(availableDateFormat),new SimpleDateFormat(availableDateFormat) };@Overridepublic Object convertFromString(Map context, String[] paramFromBrowser,Class targetClass) {if (java.util.Date.class == targetClass) {java.util.Date date = null;String dateString = paramFromBrowser;for (SimpleDateFormat dateFormatter : sdf) {try {date = dateFormatter.parse(dateString);} catch (Exception e) {}}if (date == null)return new java.util.Date();elsereturn date;}return null;}@Overridepublic String convertToString(Map arg0, Object source) {String dateString = "";if (source instanceof java.util.Date) {Date date = (Date)source;for (SimpleDateFormat dateFormatter : sdf) {try {dateString = dateFormatter.format(date);} catch (Exception e) {}}}return dateString;}}
页: [1]
查看完整版本: structs 类型转换