使用统一返回响应,出现String类型转换失败的问题

news2025/2/28 5:18:07

使用统一返回响应,出现String类型转换失败的问题

  • 问题描述
  • 解决方案
    • 1、替换fastjson转换器
    • 2、在统一响应中,对String类型特殊处理
    • 3、加入Jackson转换器解决(同时可关闭Zalando的堆栈打印)

问题描述

在对项目框架进行升级处理的时候,对统一响应进行了封装。在这里插入图片描述
但是测试发现,在返回String类型的时候出现了问题

    @RequestMapping("/normal")
    public String normal() {
        return "nor";
    }
java.lang.ClassCastException: class com.zck.power.domain.vo.HttpResponse cannot be cast to class java.lang.String (com.zck.power.domain.vo.HttpResponse is in unnamed module of loader 'app'; java.lang.String is in module java.base of loader 'bootstrap')
	at org.springframework.http.converter.StringHttpMessageConverter.addDefaultHeaders(StringHttpMessageConverter.java:44)
	at org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:211)
	at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:293)
	at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:181)
	at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:78)
	at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:124)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
	at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
	at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
	at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:113)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
	at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
	at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
	at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at com.zck.power.security.filter.JwtFilter.doFilterInternal(JwtFilter.java:57)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
	at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
	at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
	at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
	at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
	at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
	at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
	at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:97)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:41002)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.base/java.lang.Thread.run(Thread.java:834)

从报错的日志信息中可以看到是由于StringHttpMessageConverter在对String进行转换的时候出现了问题。当Controller的方法返回值类型为String,HttpMessageConverter使用的是StringHttpMessageConverter,但我们通过统一响应拦截后,返回的对象类型为HttpResponse这个自定义的类型。就出现了上图中出现的问题。

解决方案

1、替换fastjson转换器

@Bean
public HttpMessageConverters custHttpMessageConverter() {
    return new HttpMessageConverters(new FastJsonHttpMessageConverter());
}

2、在统一响应中,对String类型特殊处理

 @Override
    @SuppressWarnings("all")
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        HttpResponse<Object> response = HttpResponse.ok();
        if (o == null) {
            return response;
        } else if (o instanceof DefaultProblem) {
            //  拦截异常,直接返回异常内容,不进行包装
//            response = HttpResponse.ok(((DefaultProblem) o).getStatus().getStatusCode(), ((DefaultProblem) o).getTitle(), ((DefaultProblem) o).getDetail());
            return o;
        } else if (o instanceof HttpResponse) {
            response = (HttpResponse<Object>) o;
        } else if (methodParameter.getParameterType().isAssignableFrom(String.class)) {
            response.setData(o);
            return JSON.toJSONString(response);
        } else {
            response.setData(o);
        }
        return response;
    }

3、加入Jackson转换器解决(同时可关闭Zalando的堆栈打印)

在WebMvcConfig配置文件中,加入Jackson的Converter

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        ObjectMapper mapper = Jackson2ObjectMapperBuilder.json()
                .modules(new ProblemModule(), new ConstraintViolationProblemModule()).build();

        converters.add(new MappingJackson2HttpMessageConverter(mapper));
    }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/361258.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

数据存储(整型数据存储)

目录 一、 数据类型详细介绍 1.类型的基本归类 二、 整形在内存中的存储 1.原码、反码、补码 对于整形来说&#xff1a;数据存放内存中其实存放的是补码。 三、大小端字节序介绍及判断 1、大端小端&#xff1a; 2、写出一个判断大小端的程序 四、练习整型存储 8个练习…

基于微信公众号(服务号)实现扫码自动登录系统功能

微信提供了两种方法都可以实现扫描登录。 一种是基于微信公众平台的扫码登录&#xff0c;另一种是基于微信开放平台的扫码登录。 两者的区别: 微信开放平台需要企业认证才能注册&#xff08;认证费用300元&#xff0c;只需要认证1次&#xff0c;后续不再需要进行缴费年审&#…

Python制作9行最简单音乐播放器?不,我不满足

嗨害大家好鸭~我是小熊猫 好久不见啦~这次就来给大家整个大福利 ~ 源码资料电子书:点击此处跳转文末名片获取 最简单的9行代码音乐播放器如下&#xff1a; import time import pygamefile r歌曲路径 pygame.mixer.init() print(正在播放,file) track pygame.mixer.music.lo…

遗传算法及Python实现

0 建议学时 4学时 1 人工智能概述 2020中国人工智能产业年会在苏州召开&#xff0c;会上发布的《中国人工智能发展报告2020》显示&#xff0c;过去十年(2011-2020) &#xff0c;中国人工智能专利申请量达389571件&#xff0c;占全球总量的74.7%&#xff0c;位居世界第一。 报…

Power BI 数据处理介绍(数据初始调整、合并列及查看数据结构)

本系列的文章&#xff1a; 安装流程和示例介绍&#xff1a; 《Power BI windows下载安装流程&#xff09;》《Power BI 11个必学官方示例数据案例&#xff08;附下载链接&#xff09;》 数据导入阶段介绍&#xff1a; 《Power BI 数据导入&#xff08;SQL Server、MySQL、网页…

1802908-00-4,Dde Biotin-PEG4-alkyne,炔烃PEG4生物素Dde

Dde Biotin-PEG4-alkyne&#xff0c;Alkyne-PEG4-Biotin Dde&#xff0c;Dde 生物素-PEG4-炔烃&#xff0c;Dde 生物素PEG4炔基&#xff0c;炔烃PEG4生物素DdeProduct structure&#xff1a;Product specifications&#xff1a;1.CAS No&#xff1a;1802908-00-42.Molecular fo…

leetcode 540. Single Element in a Sorted Array(排序数组中的单个元素)

给一个已经排好序的升序数组&#xff0c;其中每个元素都会重复2次&#xff0c;只有一个元素只有一个&#xff0c; 找出这个只有一个的元素。 要求时间复杂度在O(logn), 空间复杂度在O(1). 思路&#xff1a; 时间复杂度为O(logn), 让人想到了binary search. 因为时间复杂度为…

keil5安装了pack包但是还是不能选择device

一开始&#xff0c;我以为是keil5无法安装 STM32 芯片包&#xff0c;打开device倒是可以看到stm公司的芯片包&#xff0c;但是没有我想要的stm32f1。 我按照网上的一些说法&#xff0c;找到了这个STM32F1 的pack芯片包&#xff0c;但是我双击安装的时候&#xff0c;它的安装位…

(HP)新手引导使用react-shepherd

1&#xff0c;官方参数文档&#xff1a;https://shepherdjs.dev/docs/tutorial-02-usage.html 2&#xff0c;基本代码 import { ShepherdTour } from react-shepherd; import ./index.less; // 自己的样式文件&#xff0c;用来修改样式 import ./shepherd.less; // 将shephe…

嵌入式C语言自我修养:从芯片、编译器到操作系统-习题、笔记

前沿 C语言测试(1):基本概念考查 什么是标识符、关键字和预定义标识符? 三者有何区别? 标识符&#xff08;Identifier&#xff09;:由程序员定义&#xff0c;用来表示变量&#xff0c;包括了变量名、函数名、宏名、结构体名等。 标识符的命名规范&#xff1a;C语言规定&…

Android架构设计——【 APT技术实现butterknife框架 】

APT简介 APT英文全称&#xff1a;Android annotation process tool是一种处理注释的工具&#xff0c;它对源代码文件进行检测找出其中的Annotation&#xff0c;使用Annotation进行额外的处理。 Annotation处理器在处理Annotation时可以根据源文件中的Annotation生成额外的源文…

100种思维模型之启发式偏差思维模型-017

曾国藩在给儿子的一封家书中曾写道&#xff1a;余于凡事皆用困知勉行工夫&#xff0c;尔不可求名太骤&#xff0c;求效太捷也。熬过此关&#xff0c;便可少进。再进再困&#xff0c;再熬再奋&#xff0c;自有亨通精进之日。 不急躁不求捷径&#xff0c;小火慢炖&#xff0c;将事…

burp小程序抓包

身为一名码农&#xff0c;抓包肯定是一项必备技能。工作中遇到很多次需要对小程序进行抓包排查问题。下面分享一下我的抓包方式&#xff0c;使用的是电脑版小程序抓包&#xff0c;跟手机的方式都差不多的。 一、环境 微信版本&#xff1a;3.6.0.18 Burpsuite版本&#xff1a…

Python容器

容器 容器是一种可以容纳多份数据的数据类型&#xff0c;容纳的每一份数据称之为1个元素&#xff0c;每一个元素&#xff0c;可以是任意类型的数据&#xff0c;如字符串、数字、布尔等。 数据容器根据特点的不同&#xff0c;如&#xff1a; 是否支持重复元素是否可以修改是否…

k8s1.17.2+centos7.7+docker18.06

1.简介 1.1pod网络 总述&#xff1a;Kubernetes 的网络模型假定了所有Pod都在一个可以直接连通的扁平的网络空间中 Flannel&#xff1a;基于L2&#xff0c;构建用于各个pod通信的网络架构。使用iptables进行数据包过滤。Calico&#xff1a;纯L3&#xff0c;构建用于各个pod通…

【Java基础】反射

概述 引入 package ref;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r…

VUCA项目环境中如何提升项目进度计划与控制工作有效性的系统思考【一杯咖啡谈项目】

VUCA环境下&#xff0c;项目进度延迟是经常遇见的问题&#xff0c;如何解决此类问题&#xff1f;今天分享一个案例&#xff0c;在这个案例中&#xff0c;基于“根因分析法”&#xff0c;对某主题客户端项目的进度延迟问题进行了分析&#xff0c;找到根本原因&#xff0c;提出了…

鼠标指针文件格式解析

鼠标指针文件格式解析 文章目录鼠标指针文件格式解析windowsico文件格式分析文件头&#xff1a;图像数据头段&#xff1a;图像数据段&#xff1a;Ani动态光标格式解析数据结构&#xff1a;anihseq **rate**LISTcur静态光标文件格式解析macOSLinuxwindows ico文件格式分析 是一…

2023年PMP考试复习攻略

如何备考PMP呢&#xff1f; 这本书是PMP认证考试的官方教材&#xff0c;体系完善&#xff0c;可以迅速帮助入门者搭建项目管理知识体系&#xff0c;备考PMP考试的伙伴&#xff0c;这本书一定要读一遍&#xff01; 经验都是积累出来的&#xff0c;交流小队里有很多分享面试经验…

Vue3 中生命周期的使用

目录前言&#xff1a;一、什么是生命周期函数二、什么是 Keep-Alive 组件三、生命周期函数分为几种&#xff0c;分别有什么用&#xff1f;1. beforeCreate2. created3. beforeMount/onBeforeMount4. mounted/onMounted5. beforeUpdate/onBeforeUpdate6. updated/onUpdated7. be…