web.xml中要有以下条目
<context-param>
<param-name>datePattern</param-name>
<param-value>yyyy-MM-dd</param-value>
</context-param>
public class TypeConversionExample extends ActionSupport{
private static final long serialVersionUID = 1L;
private String name;
private int rollNo;
private double amount;
private Date submissionDate;
private String datePattern="yyyy-mm-dd";
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println(getSubmissionDate());
System.out.println(submissionDate);
return SUCCESS;
}
TypeConversionExample-conversion.properties与上诉action类在同一个包中
submissionDate=net.roseindia.converter.DateConverterClaz
amount=net.roseindia.converter.CurrencyConverterClaz
同一个包中还有错误提示properties文件,见源代码。然后就是另一个包中的类型转换类:
public class DateConverterClaz extends DefaultTypeConverter {
private Date convertedDate;
public Date convertValue(Map context, Object object, Class type) {
System.out.println("Inside Date Converter");
if (type == Date.class) {
System.out.println("inside If Block");
String datePattern = "yyyy-MM-dd";
DateFormat format = new SimpleDateFormat(datePattern);
format.setLenient(false);
try {
String[] dateString = (String[]) object;
convertedDate = format.parse(dateString[0]);
System.out.println("Today "+convertedDate);
return convertedDate;
} catch (Exception e) {
e.toString();
throw new TypeConversionException("Given Date is Invalid");
}
}
return null;
}
public class CurrencyConverterClaz implements TypeConverter{
StringBuilder stringBuilder;
public String replace(String string, char character, String convert) {
if (string == null) {
return null;
}
int length = string.length();
stringBuilder= new StringBuilder(string.length() * 2);
for (int i = 0; i < length; i++) {
char char2 = string.charAt(i);
if (char2 == character) {
stringBuilder.append(convert);
} else {
stringBuilder.append(char2);
}
}
return stringBuilder.toString();
}
@Override
public Object convertValue(Map<String, Object> arg0, Object arg1,
Member arg2, String arg3, Object value, Class type) {
// TODO Auto-generated method stub
if(value==null){
return null;
}
else if(type==String.class){
NumberFormat newCurrency = new DecimalFormat("#,##0.00");
String formatedCurrency=newCurrency.format((Double) value);
System.out.println(formatedCurrency);
return formatedCurrency;
}
else if ( type == Double.TYPE || type == Double.class) {
String[] strings = (String[]) value;
String doubleValue = strings[0];
return Double.parseDouble(replace(doubleValue, ',', ""));
}
return null;
}
}
为了避免中文乱码,jsp页面要有
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
原文:http://www.roseindia.net/struts/struts/struts2.2.1/typeconversionexample.html
源代码:http://pan.baidu.com/share/link?shareid=356719023&uk=3878681452