• 如何自定义类型转换器:

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:

  1. String
  2. boolean / Boolean
  3. char / Character
  4. int / Integer, float / Float, long / Long, double / Double
  5. dates - uses the SHORT format for the Locale associated with the current request
  6. arrays - assuming the individual strings can be coverted to the individual items
  7. 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.

  1. Enumerations
  2. 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(二十):自定义类型转换器的更多相关文章

  1. Struts2初学 struts2自定义类型转换器

    一.问题的引出      Struts2的类型转换是基于OGNL表达式的,由于请求的参数都是字符串,而JAVA 本身属于强类型的的语言,这样就需要把请求参数字符串转换成其他类型.     Struts ...

  2. springmvc——自定义类型转换器

    一.什么是springmvc类型转换器? 在我们的ssm框架中,前端传递过来的参数都是字符串,在controller层接收参数的时候springmvc能够帮我们将大部分字符串类型的参数自动转换为我们指 ...

  3. 《SpringMVC从入门到放肆》十二、SpringMVC自定义类型转换器

    之前的教程,我们都已经学会了如何使用Spring MVC来进行开发,掌握了基本的开发方法,返回不同类型的结果也有了一定的了解,包括返回ModelAndView.返回List.Map等等,这里就包含了传 ...

  4. Struts2框架的自定义类型转换器

    前言:对于java的基本数据类型及一些系统类(如Date类.集合类),Struts2提供了内置类型转换功能,但是也有一定的限制.所以就演示出自定义类型转换器 一.应用于局部类型转换器 eg.用户登录出 ...

  5. [原创]java WEB学习笔记67:Struts2 学习之路-- 类型转换概述, 类型转换错误修改,如何自定义类型转换器

    本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱 ...

  6. 自定义类型转换器converter

    作用:目前将日期转换成string,将string转换成我想要的类型   0509课件里讲 一.数据类型转换在web应用程序中,数据存在两个方向上的转换:1.当提交表单时  表单数据以字符串的形式提交 ...

  7. struts2自定义类型转换器

    首先,何为struts2的类型转换器? 类型转换器的作用是将请求中的字符串或字符串数组参数与action中的对象进行相互转换. 一.大部分时候,使用struts2提供的类型转换器以及OGNL类型转换机 ...

  8. struts2基础---->自定义类型转换器

    这一章,我们开始struts2中自定义类型转换器的学习. 自定义类型转换器

  9. springmvc:自定义类型转换器代码编写

    字符串转换日期: 1.自定义一个类 /** * 字符串转换日期 */ public class StringToDateConverter implements Converter<String ...

随机推荐

  1. windows下安装Virtualenvwrapper

    windows下安装Virtualenvwrapper 我们可以使用Virtualenvwrapper来方便地管理python虚拟环境,但是在windows上安装的时候.....直接 install  ...

  2. 书写Css文件要点

    1. 自定义样式名 实例1:<style type="text/css"> input.ng-invalid{ // .号一定要在对应的元素名后面, 没有空格 colo ...

  3. 利用Java生成UUID

    UUID是什么? UUID 是 通用唯一识别码(Universally Unique Identifier)的缩写,是一种软件建构的标准,亦为开放软件基金会组织在分布式计算环境领域的一部分.其目的,是 ...

  4. 桶排序/基数排序(Radix Sort)

    说基数排序之前,我们先说桶排序: 基本思想:是将阵列分到有限数量的桶子里.每个桶子再个别排序(有可能再使用别的排序算法或是以递回方式继续使用桶排序进行排序).桶排序是鸽巢排序的一种归纳结果.当要被排序 ...

  5. 关于css选择器中有小数点的标签获取

    需求说明 因为项目中章节配置的时候有小数点,1,1.1,1.2,1.11的标题,这个时候每一行标题的id,class设置成标题号是独一无二的标记.但是,直接用js获取是获取不到的,例如$('#3.22 ...

  6. Shell 判断文件或文件夹是否存在

    #shell判断文件夹是否存在 #如果文件夹不存在,创建文件夹 if [ ! -d "/myfolder" ]; then mkdir /myfolder fi #shell判断文 ...

  7. lua continue实现

    --第一种 , do while true do == then break end -- 这里有一大堆代码 -- -- break end end --第二种 i = ) do if () then ...

  8. web服务器学习4---httpd-2.4.29优化

    实验环境: 环境:CentOS 7.4 软件版本:httpd-2.4.29 一.网页压缩 1.检查是否安装压缩模块 apachectl -D DUMP_MODULES | grep deflate 如 ...

  9. IDEA配置Struts框架

    对于刚接触编程的同学,对框架只是还不是很了解,本文主要介绍在Idea上配置Struts,实现简单的页面跳转,以及页面参数传递. 在进行代码编写之前先对Idea进行一个简单了解,对于长时间接触编程的,对 ...

  10. C语言第一次作业——输入输出格式

    题目1温度转换 本题要求编写程序,计算华氏温度150°F对应的摄氏温度.计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为整型. 1.实验代码 #include& ...