struts2 类型转换之一

此处 我们通过简单的例子实现对action下的某个属性字段进行类型转换 

1)输入界面

<form action="userAction.action" method="post">
    	<input type="text" name="birthday" value=""><br>
    	<input type="submit" value="提交">
 </form>

2)测试action ----UserAction 仅仅有个类型为Date的birthday属性 

public class UserAction extends ActionSupport{
	private Date birthday;
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	@Override
	public String execute() throws Exception {
		
		return SUCCESS;
	}	
}

 3)struts.xml配置文件 配置action

<action name="userAction" class="com.etc.sky.action.UserAction">
<result>/show.jsp</result>
</action>

4)自定义类型转换器类  实现 将表单输入的字符串转化为Date类型/获取birthday值的时候 将其转换为string便于页面显示

public class DateConverstor extends StrutsTypeConverter {

	/**
	 * arg1为表单传入的参数 arg2为arg1需要转换的目标对象类型此处也即为java.util.date
	 * 该方法执行在action为属性注入值之前 即set方法之前
	 * */
	@Override
	public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
		System.out.println(arg1[0]);
		if(arg2==Date.class){
			String birth=arg1[0];
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
			try {
				Date date=sdf.parse(birth);
				System.out.println("convertFromString"+date);
				return date;
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * arg1为需要进行转换的对象 此处即为date
	 * 该方法执行在获取action属性值后 即get方法之后
	 * */
	@Override
	public String convertToString(Map arg0, Object arg1) {
		if(arg1 instanceof Date){
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
			Date date=(Date) arg1;
			String strDate=sdf.format(date);
			System.out.println("convertToString"+strDate);
			return strDate;
		}
		return null;
	}

}

5)局部类型转换资源文件配置

命名规则为:要进行类型转换的action名-conversion.properties

内容为:action下要进行类型转换的属性=类型转换器类的全称(包名+类名)

birthday=com.etc.sky.converstor.DateConverstor

 6)显示页面 注意 为了能够正常显示 转换后的信息 必须采用struts标签来读取信息

<s:property value="birthday"/>

 测试 OK.......

猜你喜欢

转载自hxlzpnyist.iteye.com/blog/1539113