分类: 系统运维
2012-01-20 14:36:22
可以使用Struts2框架自带的类型转换器StrutstypeConverter简化类型转换代码的编写,StrutsTypeConverter继承于DefaultTypeConverter弗雷,并且提供了两个抽象方法:converFromString与converToString,分别表示从页面的字符串转换为后台对象以及从后台对象转换为页面的字符串,我们只需实现这个两个抽象方法即可实现类型转化(省略了条件分支的编写)
Class StrutsTypeConverter的API
Method Summary | |
abstract |
convertFromString( context, [] values, toClass) |
abstract |
convertToString( context, o) |
|
convertValue( context, o, toClass) |
protected |
performFallbackConversion( context, o, toClass) |
UserConverter2.java
package com.shengsiyuan.converter;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.struts2.util.StrutsTypeConverter;
import com.shengsiyuan.bean.User;
public class UserConverter2 extends StrutsTypeConverter
{
//StrutsTypeConverter只是将if toClass ==...else if...进行了封装
@Override
public Object convertFromString(Map context, String[] values, Class toClass)
{//fromstring,即从页面字符串转到后台
User user = new User() ;
String value = values[0] ;
StringTokenizer st = new StringTokenizer(value,";") ;
user.setUsername(st.nextToken()) ;
user.setPassword(st.nextToken()) ;
return user ;
}
@Override
public String convertToString(Map context, Object o)
{
// 后台往字符串转,即后台往页面转
User user = (User)o ;
String username = user.getUsername() ;
String password = user.getPassword() ;
String userInfo = "username:" +username+"password:"+password ;
return userInfo ;
}
}
UserActoin-conversion.properties
#user=com.shengsiyuan.converter.UserConverter
user=com.shengsiyuan.converter.UserConverter2