zoukankan      html  css  js  c++  java
  • struts2类型转换

    struts2里面不使用ActionForm来接收参数,而是在Action中定义一个与请求参数同名的属性就能接收到表单中的参数。jsp页面上通过el表达式来取得Action中属性的值。

    如果在一个类中包含了另一个类作为参数,那么在form表单中定义属性名称的时候就需要使用对象来指定了,比如form中的input的name为Person.id,在el中也要使用Person.id获取数据。

    struts2中有两种类型转换器:

    1,局部类型转换器:

    定义类型转换器:

    package control.center;

    import java.sql.Date;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Map;

    import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

    public class TypeConvert extends DefaultTypeConverter {

     /**
      *
      * value:表示获取的值
      * toType:表示转换的类型
      *
      */
     public Object convertValue(Map<String, Object> context, Object value,
       Class toType) {
             
      SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMdd");
       try {
       if(toType==Date.class)
       {
        String[] params=(String[])value;
        return dateFormat.parse(params[0]);
       }else if(toType==String.class)
       {
         Date date=(Date)value;
         return dateFormat.format(date);
       }
      
       } catch (ParseException e) {
               e.printStackTrace();
      }
       return null;
     }

    }

    注册局部类型转换器:

    假如需要转换数据类型的Action为HelloWorldAction,那么创建类型转换配置文件HelloWorldAction-convertion.properties,配置文件中的文本:

    birthday=com.type.DateTypeConver

    其中birthday为Action中需要转换的属性,DateTypeConver为转换器

    全局类型转换:

    只要将局部类型转换器的名称改为xwork-convertion.properties,并将该文件放置在src目录下。配置文件中的文本:

    birthday=com.type.DateTypeConver

  • 相关阅读:
    BZOJ 3506 机械排序臂 splay
    BZOJ 2843 LCT
    BZOJ 3669 魔法森林
    BZOJ 2049 LCT
    BZOJ 3223 文艺平衡树 splay
    BZOJ 1433 假期的宿舍 二分图匹配
    BZOJ 1051 受欢迎的牛 强连通块
    BZOJ 1503 郁闷的出纳员 treap
    BZOJ 1096 ZJOI2007 仓库设计 斜率优化dp
    BZOJ 1396: 识别子串( 后缀数组 + 线段树 )
  • 原文地址:https://www.cnblogs.com/jinzhengquan/p/1963330.html
Copyright © 2011-2022 走看看