Struts2中的参数传递
时间:2011-02-04
我们知道,Struts2完成参数传递处理工作的基础是OGNL和ValueStack。而在这个过程中,我也把Struts2所要做的工作大致归纳为两个方面:
1. 对OGNL操作进行封装,完成OGNL表达式所表示的值到Java对象的值传递机制
2. 在参数传递的过程中,做恰当的类型转化,保证页面上的字符串能够转化成各式各样的Java对象
接下来,通过四个不同的角度,来具体讲述Struts2在这两个方面的工作。
目 录 [ - ]
最简单的参数传递
Array、List、Map等容器类型的参数传递
文件上传
自定义的类型转化实现
最简单的参数传递
public class EnumTypeConverter extends DefaultTypeConverter {
/**
* Converts the given object to a given type. How this is to be done is implemented in toClass. The OGNL context, o
* and toClass are given. This method should be able to handle conversion in general without any context or object
* specified.
*
* @param context - OGNL context under which the conversion is being done
* @param o - the object to be converted
* @param toClass - the class that contains the code to convert to enumeration
* @return Converted value of type declared in toClass or TypeConverter.NoConversionPossible to indicate that the
* conversion was not possible.
*/
public Object convertValue(Map context, Object o, Class toClass) {
if (o instanceof String[]) {
return convertFromString(((String[]) o)[0], toClass);
} else if (o instanceof String) {
return convertFromString((String) o, toClass);
}
return super.convertValue(context, o, toClass);
}
/**
* Converts one or more String values to the specified class.
* @param value - the String values to be converted, such as those submitted from an HTML form
* @param toClass - the class to convert to
* @return the converted object
*/
public java.lang.Enum convertFromString(String value, Class toClass) {
return Enum.valueOf(toClass, value);
}
}
Struts2中的参数传递(2)
时间:2011-02-04
有了这个类,我们就可以比较轻松的对枚举类型进行数据赋值了。
Java代码
public enum Gender {
MALE, FEMALE
}
Html代码
<form method="post" action="/struts-example/enum-conversion.action">
<input type="text" name="user.name" value="downpour" />
<select name="user.gender">
<option value="MALE">男</option>
<option value="FEMALE">女</option>
</select>
<input type="submit" value="submit" />
</form>
Java代码
public class EnumConversionAction extends ActionSupport {
private static final Log logger = LogFactory.getLog(Policy.class);
private User user;
/* (non-Javadoc)
* @see com.opensymphony.xwork2.ActionSupport#execute()
*/
@Override
public String execute() throws Exception {
logger.info("user''s gender:" + use
|