当需要特定类型的参数时,需要类型转换.在某些情况下,要使用ModelDriven和Preparable接口,情况又有发生不同.

struts2中的Action实现了ModelDriven和Preparable接口,Action的属性就要写明gett/sett方法,否则仍然不能转换成功

类型转换的配置也分三种,Action,model,全.名称分别是:EmployeeAction-conversion.properties,Employee-conversion.properties,xwork-conversion.properties.其中EmployeeAction-conversion.properties中的内容也分两种写法,如

#employee.birth=com.fengye.DateConverter
#birth=com.fengye.DateConverter

 页面访问也会有

<s:form name="save" action="emp_save" method="POST">
    <s:textfield name="name" label="username" ></s:textfield>
    <s:textfield name="birth" label="birth"></s:textfield>
    <s:submit label="submit" value="submit"/>
</s:form>
<s:form name="save" action="emp_save" method="POST">
    <s:textfield name="employee.name" label="username" ></s:textfield>
    <s:textfield name="employee.birth" label="birth"></s:textfield> 
   <s:submit label="submit" value="submit"/>
</s:form>

下面的表格列出了可能出现的结果(左侧代表了页面的访问方法,EmployeeAction/Employee/xwork代表了配置文件的位置,上方的第二行代表配置文件中的内容,如:employee.birth代表了

在EmployeeAction-conversion.properties放置在EmployeeAction的同级目录下,并且内容为employee.birth=com.fengye.DateConverter)

使用paramsPrepareParamsStack

 

 

 

EmployeeAction

Employee

xwork

employee.birth

birth

birth

java.util.Date

 

无异常

转换

无异常

转换

无异常

转换

无异常

转换

name="birth"

"employee.birth"

使用paramsPrepareParamsStack修改 PrepareInterceptor 拦截器的 alwaysInvokePrepare 属性值为 false

 

EmployeeAction

Employee

xwork

employee.birth

birth

birth

java.util.Date

 

无异常

转换

无异常

转换

无异常

转换

无异常

转换

name="birth"

"employee.birth"

使用默认拦截器defaultStack

 

EmployeeAction

Employee

xwork

employee.birth

birth

birth

java.util.Date

 

无异常

转换

无异常

转换

无异常

转换

无异常

转换

name="birth"

"employee.birth"

不使用ModelDriven

 

EmployeeAction

Employee

xwork

employee.birth

birth

birth

java.util.Date

 

无异常

转换

无异常

转换

无异常

转换

无异常

转换

name="birth"

不能访问

"employee.birth"

public class DateConverter extends StrutsTypeConverter {
    public Object convertFromString(Map context, String[] values, Class toClass) {
        if (values != null && values.length > 0 && values[0] != null && values[0].length() > 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            try {
                return sdf.parse(values[0]);
            }
            catch(ParseException e) {
                throw new TypeConversionException(e);
            }
        }
        return null;
    }
    public String convertToString(Map context, Object o) {
        if (o instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            return sdf.format((Date)o);
        }
        return "";
    }
}

 

posted on 2015-07-07 12:46  fengyexjtu  阅读(512)  评论(0编辑  收藏  举报