先說一下對象前端
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; }