Converter添加java.util.Date类型转换器
1 编写UtilDateConverter转换器类,
实现Converter接口的convert方法(com.sun.org.apache.commons.beanutils.Converter)
public class UtilDateConverter implements Converter {
public Object convert(Class type, Object value) {
System.out.println("UtilDateConverter.value="+value);
if(value==null){
return value;
}
if(value instanceof Date){//instanceof判断是否属于此类型
return value;
}
Date d=null;
if(value instanceof String){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
d=sdf.parse(value.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
return d;
}
}
2 利用servlet的init()方法注册转换器到ConvertUtils(com.sun.org.apache.commons.beanutils.ConvertUtils)
public class UtilDateConverterInitServlet extends HttpServlet {
public void init() throws ServletException {
System.out.println("UtilDateConverterInitServlet.init()");
ConvertUtils.register(new UtilDateConverter(),Date.class);
}
}
3 配置servlet,并设</load-on-startup>值
<servlet>
<servlet-name>UtilDateConverterInitServlet</servlet-name>
<servlet-class>com.bjsxt.servlet.UtilDateConverterInitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>UtilDateConverterInitServlet</servlet-name>
<url-pattern>/servlet/UtilDateConverterInitServlet</url-pattern>
</servlet-mapping>
------------------------------------------------------------------------
方法二:
1 编写UtilDateConverter转换器类,
实现Converter接口的convert方法(com.sun.org.apache.commons.beanutils.Converter)
(同上)
2 编写UtilDateConverterInitWithPlugIn类实现PlugIn接口的init()方法
public class UtilDateConverterInitWithPlugIn implements PlugIn {
public void destroy() {
}
public void init(ActionServlet arg0, ModuleConfig arg1)
throws ServletException {
System.out.println("UtilDateConverterInitServlet.init()");
ConvertUtils.register(new UtilDateConverter(),Date.class);
}
}
3 在struts-config.xml文件中配置<plug-in>标签
<plug-in className="com.bjsxt.servlet.UtilDateConverterInitWithPlugIn"/>
posted on 2009-11-30 08:10
junly 阅读(372)
评论(0) 编辑 收藏 所属分类:
struts2/struts1.3/JSF