zoukankan      html  css  js  c++  java
  • struts2---自定义类型转换器

    从servlet我们知道从页面获取到的参数都是string类型,但是struts2中基本的数据类型,它可以自动帮我们转化为其对应的包装类,就像获取到123,可以自动转化为Integer,但是比如2017-09-28这种字符串想要转化为Date,便不能自动转化,需要我自己定义类型转化器。

    继承DefaultTypeConverter,重写convertValue方法

    全局的类型转换器:

    放在src目录下,文件名 xwork-conversion.properties    内容:转化为某个类 = 转换器  (java.util.Date=com.bwf.action.DateConversion)

    局部:(只对某个action中进行自动转化)

    和action同级,文件名 action名字-conversion.properties  内容:某个成员变量 = 转换器

    配置文件:

    java.util.Date=com.bwf.action.DateConversion
    

     转换器:(DateConversion)

    import java.lang.reflect.Member;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Map;
    import ognl.DefaultTypeConverter;
    
    
    //import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
    
    
    public class DateConversion extends DefaultTypeConverter {
    
    	@Override
    	public Object convertValue(Map context, Object target, Member member, String propertyName, Object value,
    			Class toType) {
    
    		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    		if(toType == Date.class){
    			String[] values = (String[])value;
    			try {
    				Date date = simpleDateFormat.parse(values[0]);
    				return date;
    			} catch (ParseException e) {
    				e.printStackTrace();
    			}
    			
    		}else if(toType == String.class){
    			Date d = (Date)value;
    			return simpleDateFormat.format(d);
    		}
    		
    		return null;
    	}
    
    	
    //	@Override
    //	public Object convertValue(Map<String, Object> context, Object value, Class toType) {
    //		
    //		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    //		if(toType == Date.class){
    //			String[] values = (String[])value;
    //			try {
    //				Date date = simpleDateFormat.parse(values[0]);
    //				return date;
    //			} catch (ParseException e) {
    //				
    //				e.printStackTrace();
    //			}
    //			
    //		}else if(toType == String.class){    //结合ognl表达式 用于回显为字符串
    //			Date d = (Date)value;
    //			return simpleDateFormat.format(d);
    //		}
    //		
    //		return null;
    //		
    //	}
    
    }
    

      

      <s:property value="createTime"/>   将时间对象回显为字符串

             

  • 相关阅读:
    关于多态的一些问题
    003 关于shell基础,大数据的前期准备
    002 在大数据中基础的llinux基本命令
    013 MapReduce八股文的wordcount应用
    接口里语句的修饰问题
    Apache Rewrite url重定向功能的简单配置
    学习笔记 --- 缓存、动态页面静态化、网站优化
    使用PHP连接、操纵Memcached的原理和教程
    Apache中关于页面缓存的设置
    缓存(之一) 使用Apache Httpd实现http缓存
  • 原文地址:https://www.cnblogs.com/nijunyang/p/7608273.html
Copyright © 2011-2022 走看看