Struts(二十):自定义类型转换器
- 如何自定义类型转换器:
1)为什么需要自定义类型转化器?strtuts2不能自动完成字符串到所有的类型;
2) 如何定义类型转化器?
步骤一:创建自定义类型转化器的类,并继承org.apache.struts2.util..StrutsTypeConverter类;
步骤二:配置类型转化器(包含两种方式:基于字段的配置、基于类型的配置)
官网有类型转化器的写用法向导:http://struts.apache.org/docs/type-conversion.html
备注:从官网向导中我们知道struts2.3.13之后,是支持date类型自动转化的,看到官网上很多说date类型不可以自动转化的就需要看看文档了。
Built in Type Conversion Support
Type Conversion is implemented by XWork.
XWork will automatically handle the most common type conversion for you. This includes support for converting to and from Strings for each of the following:
- String
- boolean / Boolean
- char / Character
- int / Integer, float / Float, long / Long, double / Double
- dates - uses the SHORT format for the Locale associated with the current request
- arrays - assuming the individual strings can be coverted to the individual items
- collections - if not object type can be determined, it is assumed to be a String and a new ArrayList is created
Note that with arrays the type conversion will defer to the type of the array elements and try to convert each item individually. As with any other type conversion, if the conversion can't be performed the standard type conversion error reporting is used to indicate a problem occurred while processing the type conversion.
- Enumerations
- BigDecimal and BigInteger
- 基于字段的配置
1、在字段所在的Model(可能是Action,可能是一个JavaBean)的报下,新建一个ModelClassName-conversion.properties;
2、在ModelClassName-conversion.properties内输入键值对:fieldName=类型转换器的全类名;
3、加载时:第一次使用该转换器时创建实例;
4、类型转换器在使用过程中只实例化一次,是单例的。
基于上一篇文章《Struts(十九):类型转换、类型转换错误消息及显示》中例子上修改程序:
MyAction.java
/**
* @author Administrator
*
*/
package com.dx.actions; import java.awt.Point;
import java.util.Date; import com.opensymphony.xwork2.ActionSupport; public class MyAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private Integer age;
private Date birth;
private Point point; public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public Date getBirth() {
return birth;
} public void setBirth(Date birth) {
this.birth = birth;
} public Point getPoint() {
return point;
} public void setPoint(Point point) {
this.point = point;
} public String execute() {
System.out.println("age:" + this.age + ",birth:" + this.birth + ",point:" + this.point);
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<s:debug></s:debug>
<s:form action="myAction">
<s:textfield name="age" label="Age"></s:textfield>
<s:textfield name="birth" label="BirthDay"></s:textfield>
<s:textfield name="point" label="Point"></s:textfield>
<s:submit label="提交"></s:submit>
</s:form>
</body>
</html>
此时访问页面:index.jsp,提交表单会提示:
依照本小节的说明我们可以有两种方案配置方式来解决该问题:
新建一个conversion:com.dx.converters.PointConverter.java
package com.dx.converters; import java.awt.Point;
import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; public class PointConverter extends StrutsTypeConverter {
public PointConverter() {
System.out.println("PointConverter's constructor...");
} @Override
public Object convertFromString(Map context, String[] values, Class toClass) {
System.out.println("convertFromString..."); if (toClass == Point.class) {
if (values != null && values.length > 0 && values[0].indexOf(",") > 0) {
try {
int x = Integer.valueOf(values[0].split(",")[0]);
int y = Integer.valueOf(values[0].split(",")[1]);
return new Point(x, y);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return values;
} @Override
public String convertToString(Map context, Object o) {
System.out.println("convertToString..."); if (o instanceof Point) {
Point point = (Point) o;
return point.getX() + "," + point.getY();
}
return null;
}
}
解决方式一:
在MyAction.java包下创建一个MyAction-conversion.properties
point=com.dx.converters.PointConverter
解决方式二:
修改MyAction.java
/**
* @author Administrator
*
*/
package com.dx.actions; import com.dx.models.Member; import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; public class MyAction extends ActionSupport implements ModelDriven<Member> {
private static final long serialVersionUID = 1L;
private Member member; public String execute() {
System.out.println("age:" + member.getAge() + ",birth:" + member.getBirth() + ",point:" + member.getPoint());
return "success";
} @Override
public Member getModel() {
member = new Member(); return member;
}
}
新建com.dx.models.Member.java
/**
* @author Administrator
*
*/
package com.dx.models; import java.awt.Point;
import java.util.Date; public class Member {
private Integer age;
private Date birth;
private Point point; public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public Date getBirth() {
return birth;
} public void setBirth(Date birth) {
this.birth = birth;
} public Point getPoint() {
return point;
} public void setPoint(Point point) {
this.point = point;
}
}
在com.dx.models包下创建Member-conversion.properties文件
point=com.dx.converters.PointConverter
- 基于类型的配置
1、在src下新建一个xwork-conversion.properties文件;
2、在文件xwork-conversion.properties中键入键值对:待转换的类型=类型转换器的全类名;
3、加载时:在当前struts2应用程序被加载时创建实例。
备注:因此如果在web.xml配置了context-param,读取参数时,需要通过get方法中获取,否则如果在constructor中获取context-param参数,将会导致读取不到context-param配置信息。
基于上边方案二修改出解决方案三:
1、把com.dx.models包下的Member-conversion.properties转移到工程根目录(目的使其不起作用),在src下创建文件xwork-conversion.properties
2、编辑文件xwork-conversion.properties内容
java.awt.Point=com.dx.converters.PointConverter

Struts(二十):自定义类型转换器的更多相关文章
- Struts2初学 struts2自定义类型转换器
一.问题的引出 Struts2的类型转换是基于OGNL表达式的,由于请求的参数都是字符串,而JAVA 本身属于强类型的的语言,这样就需要把请求参数字符串转换成其他类型. Struts ...
- springmvc——自定义类型转换器
一.什么是springmvc类型转换器? 在我们的ssm框架中,前端传递过来的参数都是字符串,在controller层接收参数的时候springmvc能够帮我们将大部分字符串类型的参数自动转换为我们指 ...
- 《SpringMVC从入门到放肆》十二、SpringMVC自定义类型转换器
之前的教程,我们都已经学会了如何使用Spring MVC来进行开发,掌握了基本的开发方法,返回不同类型的结果也有了一定的了解,包括返回ModelAndView.返回List.Map等等,这里就包含了传 ...
- Struts2框架的自定义类型转换器
前言:对于java的基本数据类型及一些系统类(如Date类.集合类),Struts2提供了内置类型转换功能,但是也有一定的限制.所以就演示出自定义类型转换器 一.应用于局部类型转换器 eg.用户登录出 ...
- [原创]java WEB学习笔记67:Struts2 学习之路-- 类型转换概述, 类型转换错误修改,如何自定义类型转换器
本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...
- 自定义类型转换器converter
作用:目前将日期转换成string,将string转换成我想要的类型 0509课件里讲 一.数据类型转换在web应用程序中,数据存在两个方向上的转换:1.当提交表单时 表单数据以字符串的形式提交 ...
- struts2自定义类型转换器
首先,何为struts2的类型转换器? 类型转换器的作用是将请求中的字符串或字符串数组参数与action中的对象进行相互转换. 一.大部分时候,使用struts2提供的类型转换器以及OGNL类型转换机 ...
- struts2基础---->自定义类型转换器
这一章,我们开始struts2中自定义类型转换器的学习. 自定义类型转换器
- springmvc:自定义类型转换器代码编写
字符串转换日期: 1.自定义一个类 /** * 字符串转换日期 */ public class StringToDateConverter implements Converter<String ...
随机推荐
- NGUI_Label
五.Label是标签,一般是用来显示文字使用,当然NGUI的扩展性很强,可以通过添加相关的控件组成组合控件来进行复杂功能的使用. 1. 设置字体:可以设置NGUI中的字体,也可以设置Unity中的字体 ...
- sklearn包中有哪些数据集你都知道吗?
注册了博客园一晃有3个月了,同时接触机器学习也断断续续的算是有1个月了.今天就用机器学习神器sklearn包的相关内容作为我的开篇文章吧. 本文将对sklearn包中的数据集做一个系统介绍,并简单说一 ...
- Spring配置文件中如何使用外部配置文件配置数据库连接
直接在spring的配置文件中applicationContext.xml文件中配置数据库连接也可以,但是有个问题,需要在url后带着使用编码集和指定编码集,出现了如下问题,&这个符号报错-- ...
- CXF-02: 使用CXF处理JavaBean式的复合类型和List集合类型
Cat.java: package com.war3.ws.domain; public class Cat { private Integer id; private String name; pr ...
- poj supermaket (贪心)
http://poj.org/problem?id=1456 #include<cstring> #include<iostream> #include<algorith ...
- C++单例模式的经典实现(Singleton)
C++单例经典实现 本文主要介绍C++使用中的单例的两种经典实现,基本可满足一般的使用,主要分为饿汉模式和懒汉模式两种 饿汉模式 class Singleton { public: static Si ...
- day1-计算机基础
第一单元 计算机组成原理 一.概念及过程 1.进行逻辑和数值高速计算的计算机器,有存储功能,能按照程序自动执行,且能够处理海量数据的现代化电子设备. 2.发展过程 数学运算:算盘,帕斯卡的齿轮装置, ...
- STL --> find()和find_if()
find()和find_if() 一.find()函数 find(first, end, value); // 返回区间[first,end)中第一个值等于value的元素的位置.如果没有找到匹配元素 ...
- 如何在IOS上调试Hybrid应用
最近在找关于在xcode上调试Hybrid应用的方法,比如我想进行断点调试.日志打印.屏幕适配等等,刻意去搜了下方法,虽然之前已经大致知道了,这里系统归纳一下,原文在https://developer ...
- Java集合:HashMap源码剖析
一.HashMap概述 HashMap基于哈希表的 Map 接口的实现.此实现提供所有可选的映射操作,并允许使用 null 值和 null 键.(除了不同步和允许使用 null 之外,HashMap ...