SpringMVC04_自定義數據類型轉換器

SpringMVC04_自定義數據類型轉換器


  • addDate.jsp(這裏前端會提交一個yyyy-MM-dd格式的字符串)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/converter/date" method="post">
        請輸入日期:<input type="text" name="date"/>(yyyy-MM-dd)
        <br>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>
  • ConverterHandler (從前端獲取的是String類型的字符串,但需要的參數是Date類型的數據)
package com.blu.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;

@RestController
@RequestMapping("/converter")
public class ConverterHandler {

    @RequestMapping("/date")
    public String Date(Date date){
        return date.toString();
    }
}
  • 啓動後輸入http://localhost:8080/addDate.jsp進入addDate.jsp
    在這裏插入圖片描述
    輸入2020-09-30後提交出現500錯誤(Failed to convert value of type ‘java.lang.String’ to required type ‘java.util.Date’):
    在這裏插入圖片描述
  • 添加DateConverter類並實現Converter接口:
package com.blu.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateConverter implements Converter<String,Date> {

    private String pattern;

    public DateConverter(String pattern){
        this.pattern = pattern;
    }

    @Override
    public Date convert(String s) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(this.pattern);
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
}
  • 在配置文件中配置自定義的轉換器並註冊
<!-- 配置自定義轉換器 -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
	<property name="converters">
		<list>
			<bean class="com.blu.converter.DateConverter">
				<constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
			</bean>
		</list>
	</property>
</bean>

<!-- 註冊自定義轉換器的bean -->
<mvc:annotation-driven conversion-service="conversionService">

</mvc:annotation-driven>
  • 重新運行,測試成功:
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章