先说一下对象前端
public class Book { private int id; private String bookname; private Date birthday; private BigDecimal money; .....get set.... }
前端提交过来的日期格式是:2018-09-03 15:23:55,后边在controller如何用Date直接接收这个日期数据java
1. 以form-data的格式提交
也就是在controller里是直接接收对象。像这样node
@PostMapping("/books") public int addBook(Book book) { return feign.addBook(book); }
处理方法:
方法一:
在controller里添加@InitBinder, 而后添加日期格式化方式。亲测,这种能够。
这种方式只对这个controller有效web
@InitBinder public void initDateFormate(WebDataBinder dataBinder) { dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss")); }
还能够指定要格式化的具体字段。这样若是这个controller接收好几个date类型,其中有的是yyyy-MM-dd HH:mm:ss,有的是yyyy-MM-dd,就能够分别设置
能够看下WebDataBinder这个类,功能仍是很强大spring
@InitBinder public void initDateFormate(WebDataBinder dataBinder) { dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"), "birthday"); }
方法二:
给字段添加注解@DateTimeFormatjson
public class Book { private int id; private String bookname; @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") private Date birthday; private BigDecimal money; ...... }
方法三:
使用Spring MVC的扩展接口HandlerMethodArgumentResolver。它的使用是把HttpRequest里面的参数解析成Controller里面标注了@RequestMapping方法的方法参数。app
这种等因而本身定义了一个注解处理日期格式转换,而后把这个注解加入到springMVC的HandlerMethodArgumentResolver里边ide
1) Date.java – 指定该方法参数须要特殊处理工具
@Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Date { String[] params () default ""; String pattern() default "yyyy-MM-dd HH:mm:ss"; } 2) DateHandlerMethodArgumentResolver – 处理标注了@Date注解的方法参数 public class DateHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { private String[] params; private String pattern; @Override public boolean supportsParameter(MethodParameter parameter) { boolean hasParameterAnnotation = parameter.hasParameterAnnotation(Date.class); if(!hasParameterAnnotation){ return false; } Date parameterAnnotations = parameter.getParameterAnnotation(Date.class); String[] parameters = parameterAnnotations.params(); if(StringUtils.isNoneBlank(parameters)){ params = parameters; pattern = parameterAnnotations.pattern(); return true; } return false; } @Override public Object resolveArgument(MethodParameter methodParam, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { Object object = BeanUtils.instantiateClass(methodParam.getParameterType()); BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass()); HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); for (String param : params) { String value = request.getParameter(param); if(StringUtils.isNoneBlank(value)){ SimpleDateFormat sdf = new SimpleDateFormat(this.pattern); java.util.Date date = sdf.parse(value); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if(propertyDescriptor.getName().equals(param)){ Method writeMethod = propertyDescriptor.getWriteMethod(); if(!Modifier.isPublic(writeMethod.getModifiers())){ writeMethod.setAccessible(true); } writeMethod.invoke(object, date); } } } } return object; } }
3) MyMVCConfig – 配置Spring MVC扩展测试
@Configuration @EnableWebMvc public class MyMVCConfig extends WebMvcConfigurerAdapter{ ...... @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { argumentResolvers.add(new DateHandlerMethodArgumentResolver()); } }
4) 测试
@PostMapping("/books") public int addBook(@Date(params = "birthday") Book book) { return feign.addBook(book); }
2. json格式的日期
也就是在controller里如下边这种方式接收对象,加上@RequestBody
@PostMapping("/books") public int addBook(@RequestBody Book book) { return feign.addBook(book); }
第一种方法:
使用jackson提供的注解@JsonFormat
public class Book { private int id; private String bookname; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss", locale = "zh", timezone = "GMT+8") private Date birthday; private BigDecimal money; }
第二种方法:
自定义序列化和反序列工具。这里以反序列化工具为例
先定义一个反序列化工具类
public class DateSerialzer extends JsonDeserializer<Date> { @Override public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { JsonNode node = jsonParser.getCodec().readTree(jsonParser); String now = node.asText(); Date date = null; SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { date = format.parse(now); System.out.println(date); } catch (ParseException e) { e.printStackTrace(); } return date; } }
而后在从属性上注明使用哪一个反序列化工具@JsonDeserialize(using = DateSerialzer.class),以下:
public class Book { private int id; private String bookname; @JsonDeserialize(using = DateSerialzer.class) private Date birthday; private BigDecimal money; }