赞
踩
转载自:http://cxytiandi.com/blog/detail/8101
今天在post添加数据时,由于接收参数的实体类中的日期是Date类型,导致提交到后台报错。
参数提交上来时是字符串,需要转换成日期类型才可以。
代码实现:
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.core.convert.converter.Converter;
- /**
- * 日期转换器,解决在post请求中日期类型参数自动转Date类型
- * @author yinjihuan
- *
- */
- public class StringToDateConverter implements Converter<String, Date> {
- private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
- private static final String shortDateFormat = "yyyy-MM-dd";
- private static final String dateFormat2 = "yyyy/MM/dd HH:mm:ss";
- private static final String shortDateFormat2 = "yyyy/MM/dd";
- @Override
- public Date convert(String source) {
- if (StringUtils.isBlank(source)) {
- return null;
- }
- source = source.trim();
- try {
- SimpleDateFormat formatter;
- if (source.contains("-")) {
- if (source.contains(":")) {
- formatter = new SimpleDateFormat(dateFormat);
- } else {
- formatter = new SimpleDateFormat(shortDateFormat);
- }
- Date dtDate = formatter.parse(source);
- return dtDate;
- } else if (source.contains("/")) {
- if (source.contains(":")) {
- formatter = new SimpleDateFormat(dateFormat2);
- } else {
- formatter = new SimpleDateFormat(shortDateFormat2);
- }
- Date dtDate = formatter.parse(source);
- return dtDate;
- }
- } catch (Exception e) {
- throw new RuntimeException(String.format("parser %s to Date fail", source));
- }
- throw new RuntimeException(String.format("parser %s to Date fail", source));
- }
- }

- import javax.annotation.PostConstruct;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.core.convert.support.GenericConversionService;
- import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
- import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
- import com.fangjia.amp.common.StringToDateConverter;
- @Configuration
- public class WebConfigBeans {
- @Autowired
- private RequestMappingHandlerAdapter handlerAdapter;
- /**
- * 增加字符串转日期的功能
- */
- @PostConstruct
- public void initEditableValidation() {
- ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) handlerAdapter.getWebBindingInitializer();
- if (initializer.getConversionService() != null) {
- GenericConversionService genericConversionService = (GenericConversionService) initializer.getConversionService();
- genericConversionService.addConverter(new StringToDateConverter());
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。