自定義轉換器主要是實現String類型的數據轉換爲其他類型的,當瀏覽器提交數據的時候,request中的數據都是以String類型存在的,Spring會做一些類型轉換,將這些數據轉換成我們所需要的數據類型(int、float等)。如SpringMVC——請求參數的綁定中所示,String類型的2020/01/01會被Spring轉換爲Date類型數據,而String類型的2020-01-01則無法自動轉換爲Date類型的數據,這個時候就需要我們自定義類型轉換器來滿足我們的需要。
示例代碼
編寫JSP代碼
<%@page contentType="text/html; charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>requestMapping的使用</title>
</head>
<body>
<!--自定義類型轉換器-->
<a href="account/deleteAccount?date=2020-01-01">根據日期2020-01-01刪除賬戶</a><br/>
</body>
</html>
編寫Controller代碼
package com.liang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Date;
@Controller("accountController")
@RequestMapping(path = "/account")
public class AccountController {
/**
* 更新賬戶
* @return
*/
@RequestMapping(path = "/deleteAccount")
public String deleteAccount(Date date){
System.out.println("刪除了賬戶..."+date);
return "success";
}
}
編寫自定義轉換器代碼
- 定義一個類,實現Converter接口
package com.liang.utils;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
DateFormat dateFormat = null;
try{
if (s.isEmpty()){
throw new NullPointerException("需要轉換的數據爲空");
}
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse(s);
return date;
}catch (Exception e){
throw new RuntimeException("輸入日期有誤");
}
}
}
- 在springmvc配置文件中配置類型轉換器
<!--配置自定義類型轉換器:將自定義的類型轉換器註冊到類型轉換服務中去-->
<!--配置類型轉換器工廠bean-->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<!--給工廠注入一個新的類型轉換器-->
<property name="converters">
<set>
<!--配置自定義類型轉換器-->
<bean class="com.liang.utils.StringToDateConverter"></bean>
</set>
</property>
</bean>
- 在annotation-driven標籤中引用配置的配型轉換器服務
<!--引用自定義類型轉換器-->
<mvc:annotation-driven conversion-service="conversionService"/>
Converter<S, T>接口
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.core.convert.converter;
import org.springframework.lang.Nullable;
@FunctionalInterface
public interface Converter<S, T> {
@Nullable
T convert(S var1);
}
其中參數 S:代表需要進行轉換的參數的數據類型
T:代表轉換後的數據類型
<mvc;annotation-driven>說明
在SpringMVC的各個組件中,處理器映射器、處理器適配器、視圖解析器稱爲SpringMVC的三大組件。
使用mvc:annotation-driven自動加載處理器映射器和處理器適配器,所以可在SpringMVC的配置文件中使用此標籤代替註解處理器和適配器的配置。