自定义数据绑定

1.简介

在这里插入图片描述

在这里插入图片描述

2.自定义数据绑定类型

2.1有两种形式的转化器

package com.lin.convert;

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

import org.springframework.core.convert.converter.Converter;

/**
 *自定义日期转换器
 */
public class DateConvert implements Converter<String, Date> {

	private String dataPattern="yyyy-MM-dd HH:mm:ss";
	@Override
	public Date convert(String source) {
		//格式化日期
		SimpleDateFormat sdf=	new SimpleDateFormat(dataPattern);
		try {
			return	sdf.parse(source);
		} catch (Exception e) {
			throw new IllegalArgumentException("无效的日期格式,请使用这种格式"+dataPattern);
			
		}
		
	}

}

package com.lin.convert;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.format.Formatter;

public class DateFormat implements Formatter<Date> {
		
	private String dataPattern="yyyy-MM-dd HH:mm:ss";
	private SimpleDateFormat simpleDateFormatt;
	/**
	 * 使用Format自定义日期转换器
	 */
	@Override
	public String print(Date date, Locale locale) {
		
		return new SimpleDateFormat().format(date);
	}

	@Override
	public Date parse(String source, Locale locale) throws ParseException {
		simpleDateFormatt=	new SimpleDateFormat(dataPattern);
		return simpleDateFormatt.parse(source);
	}

}

DateController 类

package com.lin.controller;

import java.util.Date;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 日期控制器类
 *
 */
@Controller
public class DateController {
	/**
	 * 使用自定义类型数据绑定日期数据
	 */
	@RequestMapping("/customDate")
	public String CustomDate(Date date) {
		System.out.println("date="+date);
		return "success";
		
	}
}

	<!-- 显示装配自定义类型转换器 -->
	<mvc:annotation-driven conversion-service="conversionService" />
<!-- 自定义类型格式化转换器配置 -->
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="formatters">
			<set>
				<bean class="com.lin.convert.DateFormat"></bean>
			</set>
		</property>
	</bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值