spring-boot前端参数单位转换

前端时间单位用的是unix时间戳,单位秒,而java后端用的是Date类型。
在request请求时,如何把前端的时间戳类型优雅的转换为后端的Date类型呢。

如果你想在response时,把后端的Date类型转换到前端的时间戳类型
可以看这篇文章java中JsonSerializer用法,前后端单位转换必备

这里我使用的是SpringBoot框架。

Controller代码

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result add(@Valid OrderForm form,
                      BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
        
        }

OrderForm对象

@Data
public class OrderForm {

    private String id;

    private String userName;
    
    private Date addTime;
}

这时,如果直接传addTime=1488264066是会报错的,提示类型不正确。
但如果你把addTime类型改成Long就可以

@Data
public class OrderForm {

    private String id;

    private String userName;
    
    private Long addTime;
}

说明spring已经帮我们做了String到Long的转换,但是没有做转换到Date类型。
我们来扩展即可。

在src/java/下建一个名字为bind的包。
下面放这3个java文件

/**
* 扩展类型转换
*/
public class CustomDateEditor extends PropertyEditorSupport {

    /**
     * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        setValue(new Date(Long.decode(text)));
    }

    /**
     * @see java.beans.PropertyEditorSupport#getAsText()
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? String.valueOf(TimeUnit.MILLISECONDS.toSeconds(value.getTime())) : "");
    }

}
/**
* 扩展web初始化的配置
*/
public class CustomDateWebBindingInitializer implements WebBindingInitializer {

    /**
     * @see org.springframework.web.bind.support.WebBindingInitializer#initBinder(org.springframework.web.bind.WebDataBinder,
     *      org.springframework.web.context.request.WebRequest)
     */
    @Override
    public void initBinder(WebDataBinder binder, WebRequest request) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor());
    }

}
/**
* 让配置在request请求时生效
*/
@Configuration
public class CustomDateEditorConfiguration {

    @Autowired
    public void setWebBindingInitializer(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
        requestMappingHandlerAdapter.setWebBindingInitializer(new CustomDateWebBindingInitializer());
    }
}

配置好后,就可以接收到Date类型的内容了,全局生效。

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,282评论 19赞 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,766评论 25赞 708
  • 作业: 1.写一两段话(如回忆一个场景),其中包含有触觉和身体感觉。 2. 以别出心裁的风格改写四大名著中的著名片...
    兰奢待阅读 456评论 1赞 1
  • 雾笼暗城水如天 川风送归消暑炎 榴花迎雨人出少 滴檐露润意潇然
    青石过客阅读 236评论 0赞 1
  • 或许有一天我会感叹多么遗憾 你学富五车却依旧不懂梨汁可以化解汤的咸或许有一天我会感叹多么心碎 你韦编三绝却依旧无法...
    宋偲瑄阅读 371评论 1赞 2

友情链接更多精彩内容