SpringMVC 配置请求参数String 转Date 全局转换器
Posted 在奋斗的大道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC 配置请求参数String 转Date 全局转换器相关的知识,希望对你有一定的参考价值。
问题描述:SpringMVC 请求接收前端发送过来的请求参数提示如下错误信息:
org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam java.util.Date]
错误含义:RequestParam 无法将String 转换为Date
RequestParam源码分析:Spring 注解面面通 之 @RequestParam参数绑定源码解析
针对上述问题的解决方法总结:
第一:使用@DateTimeFormat 注解,接收日期格式数据
- 项目编译为JDK1.7、1.8以及更高版本,会自动支持@DateTimeFormat注解 .
- 低版本的话需要引入 joda-time jar包
实战:
@ApiOperation(value = "列表:搜索客户信息", notes = "传入 用户姓名、标记")
@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "用户姓名", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "mark", value = "性别", paramType = "query", dataType = "Integer"), })
@RequestMapping(value = "/list", method = RequestMethod.GET)
public CommonResult<List<ConnectInfo>> list(@RequestParam(required = false) Long userId, @RequestParam(required = false) Long customerId,
@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDt,@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDt) {
return CommonResult.success(connectInfoService.list(userId, customerId, startDt, endDt));
}
第二:编写全局日期转换器
实战:
package com.zzg.crm.config;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
/**
* 定义系统全局转换器
*
* @author zzg
*
*/
@Configuration
public class ConversionConfig {
/**
* String->Date 日期格式转换器
*
* @author zzg
*
*/
class StringToDateConverter implements Converter<String, Date> {
private final List<DateFormat> formarts = new ArrayList<>(5);
public void init() {
formarts.add(new SimpleDateFormat("yyyy-MM"));
formarts.add(new SimpleDateFormat("yyyy-MM-dd"));
formarts.add(new SimpleDateFormat("yyyy-MM-dd hh:mm"));
formarts.add(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));
formarts.add(new SimpleDateFormat("yyyy.MM.dd"));
}
@Override
public Date convert(String value) {
// TODO Auto-generated method stub
if (StringUtils.isEmpty(value)) {
return null;
}
// 初始化formarts 数据
this.init();
value = value.trim();
try {
if (value.matches("^\\\\d{4}-\\\\d{1,2}$")) {
return formarts.get(0).parse(value);
} else if (value.matches("^\\\\d{4}-\\\\d{1,2}-\\\\d{1,2}$")) {
return formarts.get(1).parse(value);
} else if (value.matches("^\\\\d{4}-\\\\d{1,2}-\\\\d{1,2} {1}\\\\d{1,2}:\\\\d{1,2}$")) {
return formarts.get(2).parse(value);
} else if (value.matches("^\\\\d{4}-\\\\d{1,2}-\\\\d{1,2} {1}\\\\d{1,2}:\\\\d{1,2}:\\\\d{1,2}$")) {
return formarts.get(3).parse(value);
} else if (value.matches("^\\\\d{4}.\\\\d{1,2}.\\\\d{1,2}$")) {
return formarts.get(4).parse(value);
}
} catch (ParseException e) {
System.out.print(e.getMessage());
}
return null;
}
}
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
/**
* 增加字符串转日期的功能
*/
@PostConstruct
public void initEditableAvlidation() {
ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter
.getWebBindingInitializer();
if (initializer.getConversionService() != null) {
GenericConversionService genericConversionService = (GenericConversionService) initializer
.getConversionService();
genericConversionService.addConverter(new StringToDateConverter());
}
}
}
@ApiOperation(value = "分页:搜索客户信息", notes = "传入 名称、标记、第几页、页大小")
@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "名称", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "mark", value = "标记", paramType = "query", dataType = "Integer"),
@ApiImplicitParam(name = "pageNum", value = "第几页", paramType = "query", dataType = "Integer", required = true),
@ApiImplicitParam(name = "pageSize", value = "页大小", paramType = "query", dataType = "Integer", required = true), })
@RequestMapping(value = "/page", method = RequestMethod.GET)
public CommonResult<CommonPage<ConnectInfoDTO>> page(@RequestParam(required = false) Long userId, @RequestParam(required = false) Long customerId,
@RequestParam(required = false) Date startDt,@RequestParam(required = false) Date endDt,
@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
long total = connectInfoService.pageTotal(userId, customerId, startDt, endDt);
return CommonResult.success(
CommonPage.restPage(connectInfoService.page(userId, customerId, startDt, endDt, pageNum, pageSize), total, pageNum, pageSize));
}
第三:参数改为String类型,在后端处理String到Date的转换,而不是交给SpringMVC来处理。
以上是关于SpringMVC 配置请求参数String 转Date 全局转换器的主要内容,如果未能解决你的问题,请参考以下文章
Spring MVC 学习笔记 --- [SpringMVC的几个注解标签说明,获取请求数据,springmvc提供的中文乱码过滤配置]