Java实操可能出现的错误3 ---springmvc

本文探讨了在SpringMVC中自定义返回状态码的不同方法,包括使用ResponseEntity、@ResponseStatus注解以及@RestControllerAdvice。接着,详细阐述了时间序列化与反序列化的问题,分析了@DateTimeFormat和@JsonFormat的使用场景和限制,并提出了全局配置类的解决方案。此外,文章还讨论了日志记录应该放在拦截器还是过滤器,并指出了拦截器中记录开始时间的线程不安全性问题。
摘要由CSDN通过智能技术生成

1返回的状态吗不对?

在这里插入图片描述
在这里插入图片描述

1.1自定义返回状态码的方式

1.1.1 用ResponseEntity


在这里插入图片描述

1.1.2@ResponseStatus定义在异常类

在这里插入图片描述


1.1.3@ResponseStatus定义在方法上

一般重定向时候用,比如重定向到response404
在这里插入图片描述

1.1.4@RestControllerAdvice

public class CustomException extends Exception {
   

    public CustomException(String message) {
   
        super(message);
    }
}
/**
 * <h1>全局统一异常处理</h1>
 * */
@RestControllerAdvice
public class GlobalExceptionAdvice {
   

    @ExceptionHandler(value = CustomException.class)
    public ResponseEntity<GeneralResponse<String>> handleCustomException(
            HttpServletRequest request, CustomException ex
    ) {
   

        GeneralResponse<String> result = new GeneralResponse<>(0, "");
        result.setData(ex.getMessage());

        return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
    }
}
  /**
     * <h2>第四种方式自定义返回状态码</h2>
     * */
    @GetMapping("/fourth")
    public GeneralResponse<String> fourth() throws CustomException {
   
        throw new CustomException("some error");
    }

2时间序列化与反序列化

在这里插入图片描述
例子:

2.1 @DateTimeFormat

在这里插入图片描述
在这里插入图片描述
测试:
get方法可以接收到时间参数
post 方法报错
在这里插入图片描述
原因:
一般都是使用@DateTimeFormat把传给后台的时间字符串转成Date,使用@JsonFormat把后台传出的Date转成时间字符串,但是@DateTimeFormat只会在类似@RequestParam的请求参数(url拼接的参数才生效,如果是放到RequestBody中的form-data也是无效的)上生效,如果@DateTimeFormat放到@RequestBody下是无效的。

在@RequestBody中则可以使用@JsonFormat把传给后台的时间字符串转成Date,也就是说@JsonFormat其实既可以把传给后台的时间字符串转成Date也可以把后台传出的Date转成时间字符串。

2.2@JsonFormat

@JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”, timezone = “GMT+8”)
private Date time;

缺点:只支持这一种格式;yyyy-MM-dd HH:mm:ss,兼容性不好
改进:写一个通用转化器,自定义一个反序列化器

2.3@JsonDeserialize 局部

package com.imooc.spring.escape.date_se_de;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

@Slf4j
public class DateJacksonConverter extends JsonDeserializer<Date> {
   

    private static final String[] pattern = new String[
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值