Struts2 type conversion detailed

1. Based on OGNL type conversion

1Common object type conversion (struts2 internal automatic conversion)

public class TypeTo {
        //该对象为 转换对象
	private User user;

	public String execute(){
		return Action.SUCCESS;
	}
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}


public class User {
	private String name;
	private String pass;
	
	public User() {
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPass() {
		return pass;
	}
	public void setPass(String pass) {
		this.pass = pass;
	}
}
//配置action
<action name="tt" class="com.wang.typeto.TypeTo">
	<result name="success">/TypeTo/show.jsp</result>
</action>


//提交界面
<s:form action="tt">
	<s:textfield name="user.name" label="username"/>
	<s:textfield name="user.pass" label="password"/>      
	<s:submit value="getTo" />
</s:form>


//展示界面
<h1>Type To</h1>
<hr>
<s:property value="user.name"/></br>
<s:property value="user.pass"/>

2Map collection attribute type

private Map<String, User> users;

public Map<String, User> getUsers() {
	return users;
}

public void setUsers(Map<String, User> users) {
	this.users = users;
}
//提交表单(部分)
<!-- user['key'].属性 形式 为 action属性进行赋值  -->
<s:textfield name="users['one'].name" label="username1"/>
<s:textfield name="users['one'].pass" label="password1"/>  
<s:textfield name="users['two'].name" label="username2"/>
<s:textfield name="users['two'].pass" label="password2"/>      
<s:submit value="getTo" />

<!-- show -->
<!-- 获取Aciton 中属性值也通过  user['key'].属性 形式-->
<s:property value="users['one'].name"/></br>
<s:property value="users['one'].pass"/></br>
<s:property value="users['two'].name"/></br>
<s:property value="users['two'].pass"/></br>

3List collection type

private List<User> users;
	
	
public List<User> getUsers() {
	return users;
}

public void setUsers(List<User> users) {
	this.users = users;
}
<!-- user[索引].属性 -->
<s:textfield name="users[0].name" label="username1"/>
<s:textfield name="users[0].pass" label="password1"/>  
<s:textfield name="users[1].name" label="username2"/>
<s:textfield name="users[1].pass" label="password2"/>      
<s:submit value="getTo" />


<!-- show -->
<s:property value="users[0].name"/></br>
<s:property value="users[0].pass"/></br>

4 When the collection type List or Map does not specify a generic type: specify type conversion

List:

//未指定泛型(通过局部类型转换文件指定 泛型 格式 ActionName-conversion.properties 放在该       Action相同位置)
private List user; 
	
public List getUser() {
	return user;
}

public void setUser(List user) {
	this.user = user;
}

Create a *.properties file and place it under the corresponding Action (TypeTo-conversion.properties)

# format: Element_<ListPropName>=<ElementType> 
# <ListPropName> is property name of List
# <ElementType> is genericity type
Element_users=com.wang.vo.User

Map:

private Map users;

public Map getUsers() {
	return users;
}

public void setUsers(Map users) {
	this.users = users;
}

Create a *.properties file and place it under the corresponding Action (TypeTo-conversion.properties)

# Map format:
# 	Key_<MapPropName>=<KeyType>
#	Element_<MapPropName>=<ValueType>
# 	<MapPropName> is property name of Map
#	<KeyType> is key of Map
#	<ValueType> is value of Map
Key_users=java.lang.String
Element_users=com.wang.vo.User

 

2. Custom type converter

(Convert a string into a compound object)

In fact, the type conversion is based on the TypeConverter interface in the OGNL framework. The custom type converter can implement this interface, but the interface method is too complicated. Struts2 provides a DefaultTypeConverter implementation class, which can be inherited from him and override the convertValue() method to customize the type converter . (This method needs to achieve two-way conversion, not an example here) Here is an explanation of its subclass (abstract class) StrutsTypeConverter class

	private User user;
	  
  	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
public class UserConverter extends StrutsTypeConverter{

	/**
	 * 将String转换成复合类型
	 * context : 转换环境上下文
	 * values  : 需要转换的参数 为数组 因为游览器端可以进行多选项提交
	 * toClass : 目标类型
	 */
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) { 
		User user = new User();
		//User user = (User)toClass.newInstance();
		String[] userValues = values[0].split(",");
		user.setName(userValues[0]);
		user.setPass(userValues[1]);
		return user;
	}

	//将复合类型转换成String类型
	@Override
	public String convertToString(Map context, Object o) {
		User user = (User)o;
		return "[" + user.getName() + "," + user.getPass() + "]";
	}
	
}

 TypeTo-conversion.properties configuration file (this configuration is a partial Action configuration and only works for a single Action)

# Type Conversion format:
#	<propName>=<ConverterClass>
#	<propName> is property name of Action
#	<ConverterClass> is Transformation processing class
user=com.wang.typeto.UserConverter

.jsp

<s:textfield name="user"/>
<s:submit value="getTo" />
<s:property value="user.name"/></br>
<s:property value="user.pass"/></br>
<s:property value="user" />

 

{Global type converter configuration: it is not effective for a specific Action but for a specific type} You need to create the xwork-conversion.properties file and place it under WEB-INF/classes

# format :
#<proType>=<ConvertClass>
com.wang.vo.User=com.wang.typeto.UserConverter.java

 

About the use of Set collection properties in Action

        //无序集合
	private Set users;
	
	public Set getUsers() {
		return users;
	}

	public void setUsers(Set users) {
		this.users = users;
	}

Custom type conversion class

public class UserConverter extends StrutsTypeConverter{

	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		Set result = new HashSet();
		for(String value:values){
			User user = new User();
			String[] userValues = value.split(",");
			user.setName(userValues[0]);
			user.setPass(userValues[1]);
			result.add(user);
		}
		return result;
	}

	@Override
	public String convertToString(Map context, Object o) {
		if(Set.class == o.getClass()){
			Set users = (Set)o;
			String result = "[";
			for(Object obj: users){
				User user = (User)obj;
				result += "<" + user.getName() + "," + user.getPass() + ">";
			}
			return result+="]";
		}
		return "";
	}
}

TypeTo-conversion.properties configuration file

# Type Conversion format:
#	<propName>=<ConverterClass>
#	<propName> is property name of Action
#	<ConverterClass> is Transformation processing class
users=com.wang.typeto.UserConverter

# Specify Set identifier 
# Set format:
#	KeyProperty_<SetPropName>=<keyProName>
#	<propName> is property name of Action
#	<keyProName> is Set elements' element
KeyProperty_users=name

.jsp

<s:textfield name="users"/>
<s:textfield name="users"/>
<s:submit value="getTo" />



<!-- 特别注意此处的圆括号 Set集合专用 List Map 使用方括号 圆括号里面(name)为Set元素唯一标识 前面类型转换器和配置文件 进行设置的  -->
<s:property value="users('wang').name"/></br>
<s:property value="users('wang').pass"/></br>

 

2. Error handling in type conversion

Custom type conversion class override convertFromString()  

        @Override
	public Object convertFromString(Map context, String[] values, Class toClass) { 
		...
                //由于某些原因抛出类型转换异常
		throw new TypeConversionException();
	}

Should be a type conversion error, the final action will return "input" as a result

 

Configure TypeTo-conversion.properties (type converter)

users=com.wang.typeto.UserConverter

Corresponding Action

public class TypeTo extends ActionSupport {
	
	private User users;
	  
  	public User getUsers() {
		return users;
	}

	public void setUsers(User users) {
		this.users = users;
	}
	
	public String execute(){
		return Action.SUCCESS;
	}
}

 

Configure the struts.xml file to configure the input result to correspond to .jsp

        <!-- 设置src/in_zh_CN.properties 文件为全局的国际化资源文件  -->
        <constant name="struts.custom.i18n.resources" value="in" />
        <package name="TT" extends="struts-default">
		<action name="tt" class="com.wang.typeto.TypeTo">
			<result name="success">/TypeTo/show.jsp</result>
			<result name="input">/input.jsp</result>
		</action>
	</package>

 src/in_zh_CN.properties global internationalized resource file

xwork.default.invalid.fieldvalue={0}字段转换错误

typeto.jsp

<s:form action="tt">
    <s:textfield name="users"/>
    <s:submit value="getTo" />
</s:form>

input.jsp

<s:fielderror/>
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==

 

 

Guess you like

Origin blog.csdn.net/weixin_41237676/article/details/84142386