日期:2014-05-20  浏览次数:20754 次

如何把一个类里所有的String的属性的内容,全部强制转换为GBK?
有一个UserInfo类,它有若干属性,例如用户名,密码,地址等
private   String   userName;
private   String   password;
private   String   address;
...
//有若干getter和setter方法,
public   String   getUserName(){
      return   this.userName;
}

public   void   setUserName(String   userName){
      this.userName   =   userName;
}
...

在项目中,由webwork自动将客户端提交的数据,把这个对象的各个属性赋值。
原有用form提交数据的方式时正常,但当改用   ajax方式提交数据时,属性中的中文内容出现乱码。
现在想在webwork的action中再把这个对象的所有是字符串类型的属性的值,强制转换为   GBK   字符集。

有没有方法能遍历这个userInfo对象中的所有属性,并将其中是String类型的属性的值,强制转换为GBK呢?

请大侠们指导。百分感谢~~!  



------解决方案--------------------
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;

public class BeanInfoWrapper
{
private static Logger logger = Logger.getLogger(BeanInfoWrapper.class);

/**
* 将指定的值赋值给指定的bean的指定属性。所指定的bean对象必须符合bean的方法命名规则
*
* @param bean
* @param propertyName
* @param values
*/
public static void setPropertyValue(Object bean, String propertyName,
Object value)
{
BeanInfo beanInfo = null;
try
{
beanInfo = Introspector.getBeanInfo(bean.getClass());
} catch (IntrospectionException e)
{
logger.error( "获取bean信息时出错 ");
e.printStackTrace();
}
MethodDescriptor[] methods = beanInfo.getMethodDescriptors();
PropertyDescriptor[] properties = beanInfo.getPropertyDescriptors();
for (int i = 0; i < properties.length; i++)
{
if (propertyName.equals(properties[i].getDisplayName()))
{
Method writeMethod = properties[i].getWriteMethod();
try
{
writeMethod.invoke(bean, new Object[] { value });
} catch (IllegalArgumentException e1)
{
logger.error( "属性值与属性的setter方法参数不一致 ");
e1.printStackTrace();
} catch (IllegalAccessException e1)
{
logger.error( "没有指定属性的setter方法 ");
e1.printStackTrace();
} catch (InvocationTargetException e1)
{
logger.error( "引用属性的setter方法出错 ");
e1.printStackTrace();
}
}
}
}

/**
* 获得指定bean的指定属性值。所指定的bean对象必须符合bean的方法命名规则
*
* @param bean
* @param propertyName
* @return
*/
public static Object getPropertyValue(Object bean, String propertyName)
{
Object retVal = null;
BeanInfo beanInfo = null;
try
{
beanInfo = Introspector.getBeanInfo(bean.getClass());
} catch (IntrospectionException e1)
{
logger.error( "获取bean信息时出错 ");
e1.printStackTrace();
}