struts2自定义类型转换器

1.局部转换器

日期转换器类:DateConverter .java

package com.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.util.StrutsTypeConverter;


/**
* 自定义日期转换类。
* @author qcd
* 2010-08-25
*/
public class DateConverter extends StrutsTypeConverter {

/**
* 从String到Date,到Action
*/
@SuppressWarnings("unchecked")
@Override
public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
   if (arg1 != null && !arg1.equals("") && arg1.length > 0) {
    String dateString = arg1[0];
    System.out.println("converter:"+dateString);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    try {
     Date dtt= sdf.parse(dateString);
     return dtt;
    } catch (ParseException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   return null;
}

/**
* 从Date到String(页面输出)
*/
@SuppressWarnings("unchecked")
@Override
public String convertToString(Map arg0, Object arg1) {
   SimpleDateFormat sdf = new SimpleDateFormat();
   return sdf.format(arg1);
}

}

javabean:User.java

package com.tw.login.bean;

import java.util.Date;

public class User {
private Date birthday;
public Date getBirthday() {
   return birthday;
}
public void setBirthday(Date birthday) {
   this.birthday = birthday;
}
}

Action:DateAction.java

package com.date.action;

import com.opensymphony.xwork2.ActionSupport;
import com.tw.login.bean.User;

/**
* 使用自定义类型转换器转换日期字符串。
* @author qcd
* 2010-08-25
*/
public class DateAction extends ActionSupport {

private static final long serialVersionUID = 1L;
private User user;

public User getUser() {
   return user;
}

public void setUser(User user) {
   this.user = user;
}

public String execute() {
   return INPUT;
}

public String save() {
   System.out.println("save:"+this.user.getBirthday());
   return SUCCESS;
}
}
在与DateAction.java同包下新建文件DateAction-conversion.properties,内容如下:

user.birthday=com.common.util.DateConverter

jsp:dateconverter.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>使用Struts2的自定主类型转换器</title>
</head>
<body>
<s:form action="/test/dateconverter.action">
   <s:textfield name="user.birthday" label="输入生日"></s:textfield>
   <s:submit value="提交"></s:submit>
</s:form>
</body>
</html>

你可能感兴趣的:(struts)