mvc自定义日期转换器
生活随笔
收集整理的這篇文章主要介紹了
mvc自定义日期转换器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 配置編碼過濾器
1, web.xml中設置配置spring mvc提供的編碼過濾器,解決get/post提交過來的數據亂碼問題
<!--配置編碼過濾器--><filter><filter-name>characterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>characterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>2. 獲取請求參數,參數綁定注解
http://127.0.0.1:8080/spring_mvc_01/user/save13?name=123
/*** 利用name來映射username* required false 可不提供參數,否則400* @param username*/@RequestMapping(value = "/save13")@ResponseBodypublic void save13(@RequestParam(value = "name", defaultValue = "bitqian", required = false) String username) {System.out.println(username);}3. 獲得請求參數,自定義類型轉換器
實現步驟: 1. 定義轉換器類實現converter接口 2. 在配置文件中聲明轉換器 3. 在,<annotation-driven>中引用轉換器1,自定義日期轉換器
package com.bitqian.convertor;import org.springframework.core.convert.converter.Converter;import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List;/*** 自定義日期轉換器* @author echo lovely* @date 2020/9/2 22:01*/ public class DateConverter implements Converter<String, Date> {@Overridepublic Date convert(String s) {List<DateFormat> dateList = new ArrayList<>();dateList.add(new SimpleDateFormat("yyyy-MM-dd"));dateList.add(new SimpleDateFormat("yyyy/MM/dd"));dateList.add(new SimpleDateFormat("yyyy.MM.dd"));Date date = null;for (int i = 0; i < dateList.size(); i++) {try {// 支持 -- // ..日期格式的轉換date = dateList.get(i).parse(s);return date;} catch (ParseException e) {// e.printStackTrace();continue;}}return null;}public static void main(String[] args) {DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");try {Date date = dateFormat.parse("2020/4/4");System.out.println(date);} catch (ParseException e) {e.printStackTrace();}} }2,spring mvc配置
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/><!--日期轉換器--><bean id="conversionServiceFactoryBean"class="org.springframework.context.support.ConversionServiceFactoryBean"><property name="converters"><list><bean class="com.bitqian.convertor.DateConverter"></bean></list></property></bean>3,測試日期轉換器
/*** 測試日期轉換器*/@RequestMapping(value = "/save14")@ResponseBodypublic void save14(Date date) {System.out.println(date);}總結
以上是生活随笔為你收集整理的mvc自定义日期转换器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何在vsc上下载php扩展包,正确的
- 下一篇: python程序设计应用教程pdf_py