SpringMVC在controller里如何接收字符串类型的日期

先说一下对象

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直接接收这个日期数据

1. 以form-data的格式提交

也就是在controller里是直接接收对象。像这样

 @PostMapping("/books")
 public int addBook(Book book) {
     return feign.addBook(book);
 }

处理方法:
方法一:
在controller里添加@InitBinder, 然后添加日期格式化方式。亲测,这种可以。
这种方式只对这个controller有效

@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这个类,功能还是很强大

@InitBinder
public void initDateFormate(WebDataBinder dataBinder) {
    dataBinder.addCustomFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"), "birthday");
}

方法二:
给字段添加注解@DateTimeFormat

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方法的方法参数。

这种等于是自己定义了一个注解处理日期格式转换,然后把这个注解加入到springMVC的HandlerMethodArgumentResolver里边

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值