springMVC自定義數據綁定-Converter

Converter 

函數式接口

å¨è¿éæå¥å¾çæè¿°

能夠將任意類型轉換爲指定的任意類型:
S是源類型,T是目標類型。
比如字符串->日期


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

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

public class DateConverter implements Converter<String, Date>{

	private String pattern = "yyyy-MM-dd HH:mm:ss,s";
	
	@Override
	public Date convert(String arg0) {
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
		try{
			return simpleDateFormat.parse(arg0);
		} catch(ParseException parseException) {
			throw new IllegalArgumentException("this pattern"+pattern);
		}
	}

}

配置文件添加配置

<!-- 顯示的裝配自定義類型轉換器 -->
	<mvc:annotation-driven conversion-service="conversionService">
	</mvc:annotation-driven>
	<!-- 自定義類型轉換器配置 -->
	<bean id="conversionService"
		class="org.springframework.context.support.ConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<bean class="my_convert.DateConverter"></bean>
			</set>
		</property>
	</bean>
 

 頁面

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>converter Date</title>
</head>
<body>
	<form action="test/getDate" method="get">
		<input type="text" name="date"><br/>
		<input type="submit" value="提交">
	</form>
</body>
</html>
 

controller

    @RequestMapping("/toDate")
	public String toDate(){
		return "date";
	}
	
	@RequestMapping("/getDate")
	public String converterDate(Date date,Model model){
		model.addAttribute("message", date);
		return "first";
	}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章