zoukankan      html  css  js  c++  java
  • Spring(十四) 类型转换器

    自定义日期类型转换器:

    1.jsp页面:

    2.定义一个类:

    3.写一个类实现Converter<String,Date>

    string,Date原本是S,T,自己改

    public class MyConverter implements Converter<String,Date> {
    
        public Date convert(String str) {
            SimpleDateFormat sdf =  getDate(str);
            try {
                return sdf.parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
    
        }
    
        private SimpleDateFormat getDate(String str) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
            if (Pattern.matches("^\d{4}-\d{1,2}-\d{2}$",str)){
                sdf=new SimpleDateFormat("yyyy-MM-dd");
            }
            if (Pattern.matches("^\d{4}/\d{1,2}/\d{2}$",str)){
                sdf=new SimpleDateFormat("yyyy/MM/dd");
            }
            if (Pattern.matches("^\d{4}\d{1,2}\d{2}$",str)){
                sdf=new SimpleDateFormat("yyyyMMdd");
            }
            return sdf;
        }
    }

    4.配置文件:

       <context:component-scan base-package="cn.mvc.t16typeconverter"></context:component-scan>
        
        <!--试图解析器-->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/day03/"></property>
            <property name="suffix" value=".jsp"></property>
        </bean>
        <!--自定义转换器-->
        <bean id="MyConverter" class="cn.mvc.t16typeconverter.typeconverter.MyConverter"></bean>
        <!--转换服务-->
        <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
            <property name="converters" ref="MyConverter"></property>
        </bean>
        <!--注解驱动-->
        <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
  • 相关阅读:
    [转]Apache与Tomcat的关系
    [转]学习object-c,补习一下指针
    [转]深度解析苹果成功的六大原因——公众类产品学习的榜样
    datetimepicker日期时间选择器
    缓缓回到顶部效果的实现
    bootstrap4实现点击标签展示对应的内容
    禁止页面内容滚动( 禁用 ctrl
    UI中的暗黑模式
    如何通过空状态留住用户
    交互设计常用原则和定律
  • 原文地址:https://www.cnblogs.com/a157/p/8694552.html
Copyright © 2011-2022 走看看