SpringBoot 统一管理接收和返回时间格式

在很多时候我们需要在项目中接收和返回时间的格式,有时候我们需要统一管理:

一.接收java.util.Date作为参数,在yaml配置文件中统一配置

spring:
  jackson:
    default-property-inclusion: non_null
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
  mvc:
    format: 
      date: yyyy-MM-dd
      date-time: yyyy-MM-dd HH:mm:ss
      time: HH:mm:ss

这里的 default-property-inclusion 是不显示空字段设置,根据需求配置;

如果不需要单独处理也可以在字段上加入注解:

  • @JsonFormat注解为返回给前端的格式 ;
  • @DateTimeFormat注解为前端传入时间格式;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private  Date  time;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot后端进行统一限制文件类型和大小,可以使用Spring Boot的MultipartFile类,通过在控制器中添加自定义注解并结合Spring Boot的拦截器实现。 首先,可以定义一个自定义注解,例如@FileValidator,用于限制文件类型和大小。在注解中添加两个属性,一个是允许上传的文件类型(MIME类型),另一个是允许上传的文件最大大小。 然后,可以编写一个拦截器,用于拦截文件上传请求,并在拦截器中进行文件类型和大小的验证。如果验证不通过,则可以返回一个自定义的错误信息。 最后,在控制器中使用@FileValidator注解对文件上传进行限制,即可实现Spring Boot后端统一限制文件类型和大小的功能。 以下是一个示例代码: 定义自定义注解: ```java @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface FileValidator { String[] allowedTypes() default {}; // 允许上传的文件类型 long maxSize() default 0; // 允许上传的文件最大大小 } ``` 编写拦截器: ```java @Component public class FileUploadInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; MethodParameter[] methodParameters = handlerMethod.getMethodParameters(); for (MethodParameter parameter : methodParameters) { if (parameter.hasParameterAnnotation(FileValidator.class)) { MultipartFile file = ((MultipartHttpServletRequest) request).getFile(parameter.getParameterName()); if (file == null) { throw new CustomException("文件不能为空"); } FileValidator fileValidator = parameter.getParameterAnnotation(FileValidator.class); if (fileValidator.allowedTypes().length > 0 && !Arrays.asList(fileValidator.allowedTypes()).contains(file.getContentType())) { throw new CustomException("文件类型不允许"); } if (fileValidator.maxSize() > 0 && file.getSize() > fileValidator.maxSize()) { throw new CustomException("文件大小超出限制"); } } } } return true; } } ``` 在控制器中使用@FileValidator注解: ```java @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") @FileValidator(allowedTypes = {"image/jpeg", "image/png"}, maxSize = 10485760) MultipartFile file) { // 处理上传文件 } ``` 上面的示例中,@FileValidator注解用于限制文件类型为image/jpeg或image/png,大小不超过10M。拦截器会在请求到达控制器之前对文件进行验证,如果不符合要求,则会抛出CustomException异常。控制器中的@RequestParam注解用于接收上传的文件,并结合@FileValidator注解进行限制。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值