HelloWorld:
package cn.com.user; import java.util.Date; public class HelloWorld { private String message; private String savePath; private Date birthday; public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { System.out.println(birthday); this.birthday = birthday; } public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String execute() { message="我的第一个struts应用!"; return "success"; } }
过滤器:
package cn.com.user; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; public class DefaultTypeConverter extends com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter { @Override public Object convertValue(Map<String, Object> context, Object value, Class toType) { SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd"); try { if(toType==Date.class) { String[] params=(String[])value; return dateFormat.parse(params[0]); } else if(toType==String.class) { Date date=(Date)value; return dateFormat.format(date); } } catch(ParseException e) { } return null; } }
局部过滤器配置文件(名为HelloWorld-conversion.properties):
birthday=cn.com.user.DefaultTypeConverter
全局过滤器配置文件(名为xwork-conversion.properties):
java.util.Date=cn.com.user.DefaultTypeConverter
JSP界面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Struts</title> </head> <body> <!-- 调用的是getMessage()方法 --> ${message} <br/> ${savePath} <br/> ${birthday} </body> </html>
struts配置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> <!-- 设定访问的后缀名 <constant name="struts.action.extension" value="do,action"></constant> --> <package name="struts" namespace="/test" extends="struts-default"> <action name="helloworld" class="cn.com.user.HelloWorld" method="execute"> <param name="savePath">/image</param><!-- 这是为了action的属性注入值 --> <result name="success">/WEB-INF/userOK.jsp</result> </action> </package> </struts>