- Controller層代碼
@Controller
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/handle02")
public ModelAndView handle02(Date birthday) {
//服務(wù)器時間
Date date = new Date();
//返回服務(wù)器時間到前端頁面
//封裝了數(shù)據(jù)和頁面信息的modelAndView
ModelAndView modelAndView = new ModelAndView();
//addObject 其實是向請求域中request.setAttribute("date",date)
modelAndView.addObject("date", date);
//視圖信息(封裝跳轉(zhuǎn)的頁面信息)
modelAndView.setViewName("success");
System.out.println("date: " + date);
System.out.println("birthday" + birthday);
return modelAndView;
}
}
-
頁面訪問HTTP報400錯誤
HTTP 400 - 控制臺輸出警告
[INFO] Initializing Servlet 'springmvc'
[INFO] Completed initialization in 677 ms
[WARNING] Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2021-08-16'; nested exception is java.lang.IllegalArgumentException]
從控制臺的日志上可以看出,SpringMVC沒有找到對應(yīng)的類型轉(zhuǎn)換器。
- 自定義時間類型轉(zhuǎn)換器
實現(xiàn)Spring core包下的Converter接口,實現(xiàn)自定義轉(zhuǎn)化器
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @Version 1.0
*/
public class DateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
// 完成字符串向日期的轉(zhuǎn)換
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date parse = simpleDateFormat.parse(source);
return parse;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
修改Spring MVC配置文件,加載自定義時間類型轉(zhuǎn)換器
<!--
自動注冊最合適的處理器映射器,處理器適配器(調(diào)用handler方法)
-->
<mvc:annotation-driven conversion-service="conversionServiceBean"/>
<!--注冊自定義類型轉(zhuǎn)換器-->
<bean id="conversionServiceBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.erxiao.edu.converter.DateConverter"></bean>
</set>
</property>
</bean>
-
驗證時間類型攔截器生效
頁面正常能夠訪問,沒有錯誤信息
HTTP 請求
控制臺日志正常輸出,無異常信息
INFO] Initializing Servlet 'springmvc'
[INFO] Completed initialization in 648 ms
date: Mon Aug 16 17:49:01 CST 2021
birthdayMon Aug 16 00:00:00 CST 2021

