mvc自定义日期转换器

tech2024-10-03  31

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") @ResponseBody public 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> { @Override public 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") @ResponseBody public void save14(Date date) { System.out.println(date); }
最新回复(0)