Struts2的类型转换机制

                                                          Struts2的类型转换机制

在基于HITP 协胆的Web 应用中,客户端〈浏览器〉和服务器之间传输的都是字符串形式的数据,换句话说,服务器接收到的用户数据只能是字符串或字符数组, 但在服务器端的Java 程序中, 数据是有各种类型的,如整型( int ) 、浮点型(float ) 、日期类型( java . u ti l. Date) 等,以及各种自定义的数据类型, 因此, 在接收到客户端传来的字符串数据后, 我们还需要将这些数据转换为正确的类型

Struts2对类型转换的支持

Struts2 类型转换机制的基础是 OGNL 表达式

1.项目的整体架构

如何自定义我们自已的类型转换器

 1 package cn.hmy.converter;
 2 
 3 import java.text.DateFormat;
 4 import java.text.ParseException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 import java.util.Map;
 8 
 9 import org.apache.struts2.util.StrutsTypeConverter;
10 
11 import com.opensymphony.xwork2.conversion.TypeConversionException;
12 
13 public class DataConverter extends StrutsTypeConverter{
14     //支持转换的多种日期格式,可增加时间格式
15     private final DateFormat[] dfs={
16             new SimpleDateFormat("yyyy年MM月dd日"),
17             new SimpleDateFormat("yyyy-MM-dd"),
18             new SimpleDateFormat("MM/dd/yy"),
19             new SimpleDateFormat("yyyy.MM.dd"),
20             new SimpleDateFormat("yyMMdd"),
21             new SimpleDateFormat("yyyy/MM/dd")
22     };
23     /**
24      * 将字符串类型的变量转换成我们的目标类型
25      * */
26     @Override
27     public Object convertFromString(Map context, String[] values, Class toTypewh) {
28     
29          String datestr=values[0];//获取日期的字符串
30         for (int i = 0; i < dfs.length; i++) {
31             try {
32                 return dfs[i].parse(datestr);
33             } catch (Exception e) {
34                 continue;
35             }
36         }
37             throw new TypeConversionException();
38     }
39 
40     /**
41      * 转换为字符串类型    一般用于前台取值
42      * **/
43     @Override
44     public String convertToString(Map context, Object obj) {
45         System.out.println(obj);
46         
47         System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(obj));
48         return new SimpleDateFormat("yyyy-MM-dd").format(obj);
49     }
50 
51 }

特定类的类型转换器

+3

全局范围的类型转换器

原文地址:https://www.cnblogs.com/hmy-1365/p/5859245.html