Struts2---类型转换器
2014-05-04 22:46
453 查看
--内置转换器
转载自:http://www.cnblogs.com/wushiqi54719880/archive/2011/07/09/2101773.html
Struts提供了一些内置的类型转换器,将请求参数中的字符串转换成相应的类型。内置类型转换支持的类型如下:
String
boolean / Boolean
char / Character int / Integer, float / Float, long / Long, double / Double
Date 使用本地化的日期格式
arrays
collections
Struts根据请求参数名(基于ONGL的参数名)将转换后的值赋给相应的Action中的属性。常用格式:
1.name —— 赋值给Action中属性名为name的属性
2.bean.firstname —— 赋值给Action中属性名为bean对象的firstname属性
3. people[0].name —— 赋值给List对象的name属性
4.friends['patrick'].name —— 赋值给Map对象的name属性
示例
BuilInConvertor.jsp
BuiltInConvertorAction.java
自定义型转换器(转载自:http://aumy2008.iteye.com/blog/150202)
一、概述
在B/S应用中,将字符串请求参数转换为相应的数据类型,是MVC框架提供的功能,而Struts2是很好的MVC框架实现者,理所当然,提供了类
型转换机制。
Struts2的类型转换是基于OGNL表达式的,只要我们把HTML输入项(表单元素和其他GET/POET的参数)命名为合法的OGNL表达式,就可以充分
利用Struts2的转换机制。
除此之外,Struts2提供了很好的扩展性,开发者可以非常简单的开发自己的类型转换器,完成字符串和自定义复合类型之间的转换。总之,
Struts2的类型转换器提供了非常强大的表现层数据处理机制,开发者可以利用Struts2的类型转换机制来完成任意的类型转换。
二、实现自定义类型转换器
实现TypeCoverter接口,或者继承DefaultTypeConverter实现类(该类实现了TypeCoverter接口),通过继承该实现类来实现自己的类型转
换器。重写convertValue方法即可。
为了简化类型转换器的实现,Struts2提供了一个StrutsTypeConverter抽象类,这个抽象类是DefaultConverter的子类。实现了方法,并提
供了2个不同转换方向的方法:Object
convertToString(Map context,String[] values,Class toClass)和String convertFromString(Map context,Object o)。
三、注册应用
实现了自定义类型转换器之后,将该类型转换器注册在Web应用中,Struts2框架才可以正常使用该类型转换器。
关于类型转换器的注册方式,主要有3中:
A、注册局部类型转换器:仅仅对某个Action的属性起作用。
B、注册全局类型转换器:对所有Action的特定类型的属性都会生效。
C、使用JDK1.5的注释来注册类型转换器:通过注释方式来生成类型转换器。
1、局部类型转换器
提供如下格式的文件
文件名: ActionName-conversion.properties
内容:多个propertyName(属性名)=类型转换器类(含包名),如 date=com.aumy.DateConverter
存放位置:和ActionName类相同路径。
2、全局类型转换器
提供如下格式的文件
文件名: xwork-conversion.properties
内容: 多个“复合类型=对应类型转换器”项组成,如 java.Util.Date=com.aumy.DateConverter
存放位置:WEB-INF/classes/目录下。
四、应用示例
如果是继承DefaultTypeConverter,重写convertValue方法, 该方法介绍如下:
这个方法转换是双向的,例如页面上<s:textfield name=”user”/>对应action中的user属性:
那么表单元素string->user的转换:if(toType==User.class){把value转换成String[],得到第1个元素,封装成User对象,返回user };表单回
填时从user->string的转换: if(value instanceof User){return 字符串}
源码相关内容:
在action中有个字段是birthday是date类型,当我们传值时必须写成1999-01-01它才会自动类型转换,但在有些时候有这样的需求
要写成19990101这样默认就不会进行自动类型转换,这样我们可以写一个自定义类型转换器,实现转换需求。
Struts2有两种类型转换器:
局部:对某个action转换类型起作用
首先要自定义类型转换器:
[java] view plaincopy
public class DateTypeConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value, Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
try {
if(toType == Date.class){//当字符串向Date类型转换时
String[] params = (String[]) value;// request.getParameterValues()
return dateFormat.parse(params[0]);
}else if(toType == String.class){//当Date转换成字符串时
Date date = (Date) value;
return dateFormat.format(date);
}
} catch (ParseException e) {}
return null;
}
}
进行注册:
创建HelloWorldAction-conversion.properties文件 HelloWorldAction是要注册的action后边是规定写法
文件内容是Action中哪个属性要进行类型转换并只向的内容转换器:
birthday=cn.test.type.converter.DateTypeConverter
全局:对所有action转换类型起作用
在src下创建xwork-conversion.properties文件
内容为:java.util.Date=cn.test.type.converter.DateTypeConverter
使用类型转换注解(摘自:http://blog.sina.com.cn/s/blog_883da5580100w3bt.html)
使用类型转换注解
Struts2提供一些类型转换注解来配置转换器,从而可以替代ActionName_conversion.properties(或者是xwork_conversion.properties)文
件。Struts2类型转换注解包括:TypeConversion注解 Conversion注解 Element注解 Key注解 KeyProperty注解 CreateNull注解
1、TypeConversion注解:包括ConversionType.CLASS(类范围)和ConversionType.APPLICATION(应用程序范围)。此注解应用于属性和方法
级别。
ex:
2、Conversion注解
Conversion注解让类型转换应用到类型(Type)级别,即可以应用到类、接口或枚举声明。该注解只有一个参数conversions。
使用Conversion注解:
3、Element注解
Element注解用于指定Collection 或Map中的元素类型,该注解只有一个参数value。
如,在定义一个list类型的对象list时使用Element注解。
4、Kye注解
Kye注解用于指定Map中的Key类型,key注解只有一个参数value。
5、KeyProperty注解
KeyProperty注解指定用于索引集合元素中属性名,只有一个参数value
6、CreateIfNull注解
CreateIfNull注解指定在引用的集合元素为null时,是否让框架创建它。只有一个参数value.
struts2类型转换错误信息
要求Action类继承ActionSupport,否则无法添加错误信息!
在struts2-default.xml中package name="struts-default"的里面可以找到
在<interceptor-stack name="defaultStack">里有对上面这个拦截器的引用,如果转换失败,例如拦截器里有异常抛出,那么struts2会把错误
信息封装成fielderror放入ActionContext中,然后默认进入名为input的视图.
错误信息的国际化:
如果是自定义的转换器,某个Action特定属性转换失败:在ActionName_zh_CN.properties国际化资源文件中写
invalid.fieldvalue.属性名=提示信息即可
如果是struts2默认的类型转换器,要改变转换失败后的英文提示信息,那么在全局国际化资源文件中写:
xwork.default.invalid.fieldvalue={0}字段类型转换失败!
转载自:http://www.cnblogs.com/wushiqi54719880/archive/2011/07/09/2101773.html
Struts提供了一些内置的类型转换器,将请求参数中的字符串转换成相应的类型。内置类型转换支持的类型如下:
String
boolean / Boolean
char / Character int / Integer, float / Float, long / Long, double / Double
Date 使用本地化的日期格式
arrays
collections
Struts根据请求参数名(基于ONGL的参数名)将转换后的值赋给相应的Action中的属性。常用格式:
1.name —— 赋值给Action中属性名为name的属性
2.bean.firstname —— 赋值给Action中属性名为bean对象的firstname属性
3. people[0].name —— 赋值给List对象的name属性
4.friends['patrick'].name —— 赋值给Map对象的name属性
示例
BuilInConvertor.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> </head> <body> <form action="../typeconvert/builtin.action" method="post"> 姓名:<input type="text" name="name" /><br /> 年龄:<input type="text" name="age" /><br /> 出生日期:<input type="text" name="birthday" /><br /> 爱好:<input type="checkbox" name="hobby" value="1" title="看电影"/>看电影 <input type="checkbox" name="hobby" value="2" />看小说 <input type="checkbox" name="hobby" value="3" />AAA <br /> FirstName:<input type="text" name="nameBean.firstName" />LastName:<input type="text" name="nameBean.lastName" /><br /> <br /> List类型测试<br /> FirstName:<input type="text" name="listName[0].firstName" />LastName:<input type="text" name="listName[0].lastName" /><br /> FirstName:<input type="text" name="listName[1].firstName" />LastName:<input type="text" name="listName[1].lastName" /><br /> FirstName:<input type="text" name="listName[2].firstName" />LastName:<input type="text" name="listName[2].lastName" /><br /> Map测试:<br /> FirstName:<input type="text" name="mapName['name1'].firstName" />LastName:<input type="text" name="mapName ['name1'].lastName" /><br /> FirstName:<input type="text" name="mapName['name2'].firstName" />LastName:<input type="text" name="mapName ['name2'].lastName" /><br /> FirstName:<input type="text" name="mapName['name3'].firstName" />LastName:<input type="text" name="mapName ['name3'].lastName" /><br /> Set测试:<br> <input type="text" name="testSet" /><br /> <input type="text" name="testSet" /><br /> <input type="text" name="testSet" /><br /> <input type="submit" value="提交" /> </form> </body> </html>
BuiltInConvertorAction.java
package com.struts2.typeconvert; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import com.opensymphony.xwork2.ActionSupport; public class BuiltInConvertorAction extends ActionSupport { private int age; private Date birthday; private int[] hobby; private String name; private Name nameBean; private List<Name> listName; private Map<String, Name> mapName; private Set<Integer> testSet; @Override @Action(value="/typeconvert/builtin",results={ @Result(name="success",location="/typeconvert/BuilInConvertor.jsp",type="dispatcher"), @Result(name="input",location="/typeconvert/BuilInConvertor.jsp",type="dispatcher") }) public String execute() throws Exception { System.out.println("姓名:"+name); System.out.println("年龄:"+age); System.out.println("出生日期:"+birthday.toLocaleString()); System.out.println(nameBean.getFirstName()+" "+nameBean.getFirstName()); for(int i=0;i<hobby.length;i++){ System.out.println(" "+hobby[i]); } Iterator<Name> iter = listName.iterator(); while(iter.hasNext()){ Name name = iter.next(); System.out.println("姓名:"+name.getFirstName()+" "+name.getLastName()); } Iterator<Name> iter1 = mapName.values().iterator(); while(iter1.hasNext()){ Name name = iter1.next(); System.out.println("姓名:"+name.getFirstName()+" "+name.getLastName()); } Iterator<Integer> iter2 = testSet.iterator(); while(iter2.hasNext()){ System.out.println(iter2.next()); } return super.execute(); } //Getter and Setter method .......... }
自定义型转换器(转载自:http://aumy2008.iteye.com/blog/150202)
一、概述
在B/S应用中,将字符串请求参数转换为相应的数据类型,是MVC框架提供的功能,而Struts2是很好的MVC框架实现者,理所当然,提供了类
型转换机制。
Struts2的类型转换是基于OGNL表达式的,只要我们把HTML输入项(表单元素和其他GET/POET的参数)命名为合法的OGNL表达式,就可以充分
利用Struts2的转换机制。
除此之外,Struts2提供了很好的扩展性,开发者可以非常简单的开发自己的类型转换器,完成字符串和自定义复合类型之间的转换。总之,
Struts2的类型转换器提供了非常强大的表现层数据处理机制,开发者可以利用Struts2的类型转换机制来完成任意的类型转换。
二、实现自定义类型转换器
实现TypeCoverter接口,或者继承DefaultTypeConverter实现类(该类实现了TypeCoverter接口),通过继承该实现类来实现自己的类型转
换器。重写convertValue方法即可。
为了简化类型转换器的实现,Struts2提供了一个StrutsTypeConverter抽象类,这个抽象类是DefaultConverter的子类。实现了方法,并提
供了2个不同转换方向的方法:Object
convertToString(Map context,String[] values,Class toClass)和String convertFromString(Map context,Object o)。
三、注册应用
实现了自定义类型转换器之后,将该类型转换器注册在Web应用中,Struts2框架才可以正常使用该类型转换器。
关于类型转换器的注册方式,主要有3中:
A、注册局部类型转换器:仅仅对某个Action的属性起作用。
B、注册全局类型转换器:对所有Action的特定类型的属性都会生效。
C、使用JDK1.5的注释来注册类型转换器:通过注释方式来生成类型转换器。
1、局部类型转换器
提供如下格式的文件
文件名: ActionName-conversion.properties
内容:多个propertyName(属性名)=类型转换器类(含包名),如 date=com.aumy.DateConverter
存放位置:和ActionName类相同路径。
2、全局类型转换器
提供如下格式的文件
文件名: xwork-conversion.properties
内容: 多个“复合类型=对应类型转换器”项组成,如 java.Util.Date=com.aumy.DateConverter
存放位置:WEB-INF/classes/目录下。
四、应用示例
如果是继承DefaultTypeConverter,重写convertValue方法, 该方法介绍如下:
public Object convertValue(Map<String, Object> context,Object value, Class toType) { context: context under which the conversion is being done value: an object to be converted to the given type totype: class type to be converted to return: converted value of the type given, or value ifthe value cannot be converted to the given type.
这个方法转换是双向的,例如页面上<s:textfield name=”user”/>对应action中的user属性:
那么表单元素string->user的转换:if(toType==User.class){把value转换成String[],得到第1个元素,封装成User对象,返回user };表单回
填时从user->string的转换: if(value instanceof User){return 字符串}
源码相关内容:
在action中有个字段是birthday是date类型,当我们传值时必须写成1999-01-01它才会自动类型转换,但在有些时候有这样的需求
要写成19990101这样默认就不会进行自动类型转换,这样我们可以写一个自定义类型转换器,实现转换需求。
Struts2有两种类型转换器:
局部:对某个action转换类型起作用
首先要自定义类型转换器:
[java] view plaincopy
public class DateTypeConverter extends DefaultTypeConverter {
@Override
public Object convertValue(Map<String, Object> context, Object value, Class toType) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
try {
if(toType == Date.class){//当字符串向Date类型转换时
String[] params = (String[]) value;// request.getParameterValues()
return dateFormat.parse(params[0]);
}else if(toType == String.class){//当Date转换成字符串时
Date date = (Date) value;
return dateFormat.format(date);
}
} catch (ParseException e) {}
return null;
}
}
进行注册:
创建HelloWorldAction-conversion.properties文件 HelloWorldAction是要注册的action后边是规定写法
文件内容是Action中哪个属性要进行类型转换并只向的内容转换器:
birthday=cn.test.type.converter.DateTypeConverter
全局:对所有action转换类型起作用
在src下创建xwork-conversion.properties文件
内容为:java.util.Date=cn.test.type.converter.DateTypeConverter
使用类型转换注解(摘自:http://blog.sina.com.cn/s/blog_883da5580100w3bt.html)
使用类型转换注解
Struts2提供一些类型转换注解来配置转换器,从而可以替代ActionName_conversion.properties(或者是xwork_conversion.properties)文
件。Struts2类型转换注解包括:TypeConversion注解 Conversion注解 Element注解 Key注解 KeyProperty注解 CreateNull注解
1、TypeConversion注解:包括ConversionType.CLASS(类范围)和ConversionType.APPLICATION(应用程序范围)。此注解应用于属性和方法
级别。
ex:
private in userAge; @TypeConversion{ type = ConversionType.CLASS, key="userAge", converter="converter.AgeTypeConverter" } public void setUserAge(int userAge){ this.userAge=userAge; }
2、Conversion注解
Conversion注解让类型转换应用到类型(Type)级别,即可以应用到类、接口或枚举声明。该注解只有一个参数conversions。
使用Conversion注解:
@Conversion{ conversions={ @TypeConversion{ type = ConversionType.CLASS, key="userAge", converter="converter.AgeTypeConverter" } } } public class xxxxAction implements Serialaizable{ private in userAge; public void setUserAge(int userAge){ this.userAge=userAge; } }
3、Element注解
Element注解用于指定Collection 或Map中的元素类型,该注解只有一个参数value。
如,在定义一个list类型的对象list时使用Element注解。
@Element("model.Register.class") privaate List list;
4、Kye注解
Kye注解用于指定Map中的Key类型,key注解只有一个参数value。
@Element("model.Register.class") @Key(java.lang.String,class) private Map map;
5、KeyProperty注解
KeyProperty注解指定用于索引集合元素中属性名,只有一个参数value
@Element("model.Register.class") @KeyProperty("number") private Set books = new LinkedHashSet();
6、CreateIfNull注解
CreateIfNull注解指定在引用的集合元素为null时,是否让框架创建它。只有一个参数value.
@Element("model.Register.class") @KeyProperty("number") @CreateIfNull(true) private Set books = new LinkedHashSet();
struts2类型转换错误信息
要求Action类继承ActionSupport,否则无法添加错误信息!
在struts2-default.xml中package name="struts-default"的里面可以找到
在<interceptor-stack name="defaultStack">里有对上面这个拦截器的引用,如果转换失败,例如拦截器里有异常抛出,那么struts2会把错误
信息封装成fielderror放入ActionContext中,然后默认进入名为input的视图.
错误信息的国际化:
如果是自定义的转换器,某个Action特定属性转换失败:在ActionName_zh_CN.properties国际化资源文件中写
invalid.fieldvalue.属性名=提示信息即可
如果是struts2默认的类型转换器,要改变转换失败后的英文提示信息,那么在全局国际化资源文件中写:
xwork.default.invalid.fieldvalue={0}字段类型转换失败!
相关文章推荐
- mysql 与java时间类型
- java模拟真实用户上传文件
- 利用Mock测试Spring中Databinder
- 1016. 部分A+B (15)
- java连接MySQL数据库时常见故障问题的分析与解决
- java模拟post请求上传文件
- JAVA学习笔记-函数的复写(override)
- Java动态代理
- Eclipse 常用快捷键
- java 并发编程---安全共享对象策略
- java事务
- java.lang.ClassNotFoundException: Didn't find class "***...
- 1014. 福尔摩斯的约会 (20)
- eclipse java ee开发jsp页面需要依赖java project文件时候的JEE Module Dependencies设置
- springMVC + ajaxfileupload异步上传图片预览,裁剪并保存图片
- Spring MVC处理静态资源
- Eclipse Web开发
- LeetCode | Reverse Words in a String
- Java第一课之输出Hello world
- Eclipse Maven项目 Spring4 MVC 配置 Freemarker视图添加 templateLoaderPath 时报错