struts2学习类型转换--DefaultTypeConverter
2.对于自定义的类型转换器来说需要提供3个信息:Action名字、Action中待转换的属性名以及该属性对应的转换器。其中Action的名称是通过struts.xml属性文件获得的、Action中待转换的属性名是通过xxx-conversion.properties属性文件中的key来获取,该属性对应的转换器是通过key所对应的value来获得的。
例如:字符串与对象的相互转化。创建如下的目录结构,导入struts2相关jar包,在xml中配置PreparedAndExecuteFilter过滤器
index.jsp中代码如下:
[html]
<h1>使用分号隔开用户名和密码信息</h1>
<form action="userAction.action">
user info:<input type="text" value="" name="user"><br>
<input type="submit" value="submit"/>
</form>
struts.xml中代码如下:
[html]
<struts>
<package name="struts2" extends="struts-default">
<action name="userAction" class="com.struts.action.UserAction">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
UserAction.java中代码如下:
[java]
package com.struts.action;
import com.opensymphony.xwork2.ActionSupport;
import com.struts.bean.User;
public class UserAction extends ActionSupport{
private User user;
@Override
public String execute() throws Exception {
System.out.println(user.getUsername());
System.out.println(user.getPassword());
return SUCCESS;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
UserAction-conversion.properties中代码如下:
[java]
user=com.struts.converter.UserConverter
UserConverter.java代码如下:
[java]
<pre class="java" name="code">package com.struts.converter;
import java.util.Map;
import java.util.StringTokenizer;
import com.struts.bean.User;
import ognl.DefaultTypeConverter;
public class UserConverter extends DefaultTypeConverter{
//从页面到后台
@Override
public Object convertValue(Map context, Object value, Class toType) {
if(User.class == toType)//从页面向后台对象转换
{
String[] str = (String[])value;
String firstValue = str[0];
StringTokenizer st = new StringTokenizer(firstValue,";");
String username = st.nextToken();
String password = st.nextToken();
User user = new User();
user.setUsername(username);
user.setPassword(password);
return user;
}else if(String.class == toType){//从后台对象向页面转换
User user = (User)value;
String username = user.getUsername();
String password = user.getPassword();
String userInfo = "username: "+username+", password: "+password;
return userInfo;
}
return null;
}
}
</pre>
<pre> </pre>
<pre></pre>