简介
说明
项目中经常会有前后端时间转换的场景,比如:创建时间、更新时间等。一般情况下,前后端使用时间戳或者年月日的格式进行传递。
如果后端收到了前端的参数每次都手动转化为想要的格式实在是太麻烦了。
基于如上原因,本文用示例介绍SpringBoot全局格式配置,将前端传进来的时间戳自动转换为LocalDateTime。
测试的时间戳:1734695378358。(对应时间为:2024-12-20 19:49:38)
返回值VO统一用这个类:
package com.knife.example.business.product.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@ApiModel("商品响应类")
public class ProductVO {
@ApiModelProperty("id")
private Long id;
@ApiModelProperty("名字")
private String name;
@ApiModelProperty("库存数量")
private Integer stockQuantity;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
}
源码下载
此内容 登录 后可见!
form形式
局部方案:@InitBinder
Controller
package com.knife.example.business.product.formPartial;
import com.knife.example.business.product.vo.ProductVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import java.beans.PropertyEditorSupport;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
@Api(tags = "form形式_局部方案")
@RestController
@RequestMapping("formPartial")
public class FormPartialController {
// 局部注册参数转换器
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(LocalDateTime.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
long timestamp = Long.parseLong(text);
setValue(LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.ofHours(8)));
}
});
binder.registerCustomEditor(LocalDate.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
long timestamp = Long.parseLong(text);
setValue(LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.ofHours(8)));
}
});
}
@ApiOperation("查询")
@GetMapping("query")
public ProductVO query(ProductQueryBO productQueryBO) {
System.out.println(productQueryBO.toString());
//省略查数据库等逻辑。
//为了简便,直接虚构一个vo
ProductVO productVO = new ProductVO();
productVO.setName(productQueryBO.getName());
productVO.setCreateTime(productQueryBO.getCreateTime());
return productVO;
}
}
BO
package com.knife.example.business.product.jsonPartial;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
@Data
@ApiModel("商品查询类")
public class ProductQueryBO {
@ApiModelProperty("名字")
private String name;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
}
访问并测试:http://localhost:8080/doc.html
结果

全局方案1:InitBinder
此内容 登录 后可见!

请先 !