SpringMVC返回不带引号的字符串方案汇总

SpringMVC返回不带引号的字符串方案汇总

问题

项目使用springboot开发的,大部分出参为json,使用的fastJson。

现在有的接口需要返回一个success字符串,发现返回结果为“success”,多带了双引号。这是因为fastJson对出参做了处理。

方案一:fastJson添加string类型的解析器(推荐)

创建一个配置类

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {@Beanpublic StringHttpMessageConverter stringHttpMessageConverter(){return new StringHttpMessageConverter(StandardCharsets.UTF_8);}@Beanpublic FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();converter.setFeatures(SerializerFeature.DisableCircularReferenceDetect);converter.setCharset(StandardCharsets.UTF_8);return converter;}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {//添加字符转解析器converters.add(stringHttpMessageConverter());//添加json解析器converters.add(fastJsonHttpMessageConverter());}@Overridepublic void extendMessageConverters(List<HttpMessageConverter<?>> converters) {converters.clear();converters.add(stringHttpMessageConverter());converters.add(fastJsonHttpMessageConverter());}
}

方案二:修改springMVC配置文件(springMVC)

网上通用的办法是在springMVC配置文件spring-servlet.xml中加入如下配置项:

<mvc:annotation-driven><mvc:message-converters>  <!-- 去除返回字符串时的引号,处理字符串引号配置要放在上面! --><bean class="org.springframework.http.converter.StringHttpMessageConverter"><constructor-arg value="UTF-8" /><!-- 避免出现乱码 -->  <property name="supportedMediaTypes">  <list>  <value>text/plain;charset=UTF-8</value>  </list>  </property></bean><!-- 其他处理 -->  <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" /></mvc:message-converters> 
</mvc:annotation-driven>

也可以在applicationContext-velocity.xml,配置JSON返回模板时直接配置进去

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 返回JSON模版 --><bean id="mappingJackson2HttpMessageConverter"class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="supportedMediaTypes"><list><value>text/json;charset=UTF-8</value><!-- <value>text/html;charset=UTF-8</value> <value>application/json;charset=UTF-8</value> --></list></property></bean><bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter" /><beanclass="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"><property name="messageConverters"><list><ref bean="mappingJackson2HttpMessageConverter" /><ref bean="stringHttpMessageConverter" /></list></property></bean><!-- 配置视图的显示 --><bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">  <property name="prefix" value="/" /><property name="suffix" value=".html" /><property name="contentType" value="text/html;charset=UTF-8" /><property name="requestContextAttribute" value="request"/><!-- <property name="toolboxConfigLocation" value="/velocity-toolbox.xml" />--><property name="dateToolAttribute" value="dateTool" /><property name="numberToolAttribute" value="numberTool" /><property name="exposeRequestAttributes" value="true" /><property name="exposeSessionAttributes" value="true" /></bean>
</beans>

方案三:重写Jackson消息转换器的writeInternal方法(springMVC)

创建一个MappingJackson2HttpMessageConverter的工厂类

public class MappingJackson2HttpMessageConverterFactory {private static final Logger logger = getLogger(MappingJackson2HttpMessageConverterFactory.class);public MappingJackson2HttpMessageConverter init() {return new MappingJackson2HttpMessageConverter(){/*** 重写Jackson消息转换器的writeInternal方法* SpringMVC选定了具体的消息转换类型后,会调用具体类型的write方法,将Java对象转换后写入返回内容*/@Overrideprotected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {if (object instanceof String){logger.info("在MyResponseBodyAdvice进行转换时返回值变成String了,不能用原来选定消息转换器进行转换,直接使用StringHttpMessageConverter转换");//StringHttpMessageConverter中就是用以下代码写的Charset charset = this.getContentTypeCharset(outputMessage.getHeaders().getContentType());StreamUtils.copy((String)object, charset, outputMessage.getBody());}else{logger.info("返回值不是String类型,还是使用之前选择的转换器进行消息转换");super.writeInternal(object, type, outputMessage);}}private Charset getContentTypeCharset(MediaType contentType) {return contentType != null && contentType.getCharset() != null?contentType.getCharset():this.getDefaultCharset();}};}
}

在spring mvc的配置文件中添加如下配置

<mvc:annotation-driven><mvc:message-converters><bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"><property name="supportedMediaTypes"><list><value>image/jpeg</value><value>image/png</value><value>image/gif</value></list></property></bean><bean  factory-bean="mappingJackson2HttpMessageConverterFactory" factory-method="init"class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" ></bean></mvc:message-converters></mvc:annotation-driven><bean id="mappingJackson2HttpMessageConverterFactory" class = "com.common.MappingJackson2HttpMessageConverterFactory" />

方案四:response.getWriter().write()写到界面

 @PostMapping("/test")public void test(@RequestBody Req req, HttpServletResponse response) throw Exception{res = service.test(req);response.getWriter().write(res);response.getWriter().flush();response.getWriter().close();}

方案五:重写json的MessageCoverter

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {@Beanpublic StringHttpMessageConverter stringHttpMessageConverter() {return new StringHttpMessageConverter();}@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {converters.add(stringHttpMessageConverter());}
}
@Configuration
@Slf4j
public class WebMvcConfig extends WebMvcConfigurationSupport {/*** 使用fastjson转换器* * @param converters*/@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {super.configureMessageConverters(converters);FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();FastJsonConfig fastJsonConfig = new FastJsonConfig();fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty,SerializerFeature.DisableCircularReferenceDetect);List<MediaType> supportedMediaTypes = new ArrayList<>();supportedMediaTypes.add(MediaType.APPLICATION_JSON);supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);supportedMediaTypes.add(MediaType.APPLICATION_PDF);supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);supportedMediaTypes.add(MediaType.APPLICATION_XML);supportedMediaTypes.add(MediaType.IMAGE_GIF);supportedMediaTypes.add(MediaType.IMAGE_JPEG);supportedMediaTypes.add(MediaType.IMAGE_PNG);supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);supportedMediaTypes.add(MediaType.TEXT_HTML);supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);supportedMediaTypes.add(MediaType.TEXT_PLAIN);supportedMediaTypes.add(MediaType.TEXT_XML);fastConverter.setSupportedMediaTypes(supportedMediaTypes);fastConverter.setFastJsonConfig(fastJsonConfig);converters.add(fastConverter);}}

参考:

SpringMVC返回字符串去掉引号:https://blog.csdn.net/u013268066/article/details/51603604

Spring MVC中对response数据去除字符串的双引号:https://blog.csdn.net/qq_26472621/article/details/102678232

解决springMvc返回字符串有双引号:https://blog.csdn.net/weixin_45359027/article/details/97131384

springmvc返回不带引号的字符串:https://blog.csdn.net/weixin_34390996/article/details/92531295

SpringBoot返回字符串,多双引号:https://blog.csdn.net/baidu_27055141/article/details/91544019

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

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

相关文章

有没有免费的人才测评工具,免费的人才测评系统软件?

最近看到知乎上有个问题挺火的&#xff0c;就是问有没有免费的人才测评工具&#xff0c;人才测系统软件目前是有挺多的&#xff0c;但是要说免费&#xff0c;我还真心没有听说过&#xff0c;不但不免费&#xff0c;比较专业的人才测评公司&#xff0c;价格还是非常高的。 人才…

UOS服务器操作系统搭建离线yum仓库

UOS服务器操作系统搭建离线yum仓库 1050e版本操作系统&#xff08;适用ARM64和AMD64&#xff09;1、挂载everything镜像并同步2、配置本地仓库3、配置nginx发布离线源 1050e版本操作系统&#xff08;适用ARM64和AMD64&#xff09; 首先需要有everything镜像文件 服务端操作流…

有趣的设计模式——适配器模式让两脚插头也能使用三孔插板

版权声明 本文原创作者&#xff1a;谷哥的小弟作者博客地址&#xff1a;http://blog.csdn.net/lfdfhl 场景与问题 众所周知&#xff0c;我们国家的生活用电的电压是220V而笔记本电脑、手机等电子设备的工作压没有这么高。为了使笔记本、手机等设备可以使用220V的生活用电就需…

3、Elasticsearch功能使用

第4章 功能使用 4.1 Java API 操作 随着 Elasticsearch 8.x 新版本的到来&#xff0c;Type 的概念被废除&#xff0c;为了适应这种数据结构的改 变&#xff0c;Elasticsearch 官方从 7.15 版本开始建议使用新的 Elasticsearch Java Client。 4.1.1 增加依赖关系 <propertie…

Universal Robot (UR3)与USB摄像头和电磁夹持器结合的ROS拾取和放置硬件实施详细教程:从连接到实践

第一部分&#xff1a;连接Universal Robot (UR3)到PC 1. 将 Universal Robot (UR3) 连接到 PC (Ubuntu 16.04) 在实现机器人的自动化任务之前&#xff0c;首先需要确保机器人与计算机之间的连接是稳定的。在这一部分&#xff0c;我们将详细介绍如何将Universal Robot (UR3)连…

解决yarn下载的具体操作步骤

如何使用yarn下载依赖 概述 在软件开发中&#xff0c;我们通常需要使用到各种不同的库和框架。为了方便管理这些依赖项&#xff0c;我们可以使用包管理工具来下载和安装这些库。yarn就是一款流行的包管理工具&#xff0c;它可以帮助我们高效地管理和下载依赖。 安装yarn 在…

火花塞工作原理

1.红旗H9轿车2023款发布 2023年元旦过后&#xff0c;红旗汽车在人民大会堂举办了红旗H9的新车发布会&#xff0c;一汽红旗全新的H9豪华轿车终于出炉了全套的配置参数&#xff0c;红旗H9的车身长度达到5137mm&#xff0c;宽度1904mm&#xff0c;轴距3060mm&#xff0c;总高则控…

详细指南:使用C语言控制TI ADS1262和ADS1263模数转换器

第一部分&#xff1a;介绍与背景 TI的ADS1262和ADS1263是高精度、高分辨率的模数转换器&#xff08;ADC&#xff09;。它们广泛应用于各种精密测量应用中&#xff0c;如工业自动化、医疗设备和科研仪器。为了方便工程师和开发者使用这两款ADC&#xff0c;本文将详细介绍如何使…

2023-9-22 滑雪

题目链接&#xff1a;滑雪 #include <cstring> #include <algorithm> #include <iostream>using namespace std;const int N 310;int n, m; int h[N][N]; int f[N][N];int dx[4] {-1, 0, 1, 0}, dy[4] {0, 1, 0, -1};int dp(int x, int y) {int &v f…

读博后才知道的真道理

观点1 作者:李月亭 链接:https://www.zhihu.com/question/49608607/answer/2403947870知乎 博士毕业半年,也参加工作一段时间了,谈谈对读博的感想。 1、毕业最重要。虽然大家都知道,但是还是要特别强调一下。一定要在博士入学时就把毕业要求搞清楚。尤其是直博的,千万…

模版语法、列表渲染、文本指令、事件指令、属性指令、vue中的style和class、条件渲染、v-for能循环的

vue 基础 1 模版语法 2 文本指令 2.1 模版语法 v-text 2.2 文本指令 v-html 2.3 文本指令 v-show 2.4 文本指令 v-if 2.5 v-show把图片的显示隐藏 3 事件指令 ES6对象语法演变 3.1 v-on 不传参/a> 3.2 v-on 传参和 v-on:简写成 4 属性指令 4.1 属性指令之 v-bind: 简…

Python+Django前后端分离

程序示例精选 PythonDjango前后端分离 如需安装运行环境或远程调试&#xff0c;见文章底部个人QQ名片&#xff0c;由专业技术人员远程协助&#xff01; 前言 这篇博客针对《PythonDjango前后端分离》编写代码&#xff0c;代码整洁&#xff0c;规则&#xff0c;易读。 学习与应…

VPN协议是如何工作的

VPN&#xff0c;全名 Virtual Private Network&#xff0c;虚拟专用网&#xff0c;就是利用开放的公众网络&#xff0c;建立专用数据传输通道&#xff0c;将远程的分支机构、移动办公人员等连接起来。 VPN 通过隧道技术在公众网络上仿真一条点到点的专线&#xff0c;是通过利用…

电脑桌面透明便签软件是哪个?

在现代快节奏的工作环境中&#xff0c;许多上班族都希望能够在电脑桌面上方便地记录工作资料、重要事项、工作流程等内容。为了解决这个问题&#xff0c;一款优秀的电脑桌面便签软件是必不可少的。在选择桌面便签软件时&#xff0c;许多用户也希望便签软件能够与电脑桌面壁纸相…

携手共赴数智未来|维视智造出席2023英特尔工业物联网大会

​ ​ 9月20日&#xff0c;“数智芯生力” 2023 英特尔工业物联网大会”于上海隆重举办。作为主办方&#xff0c;英特尔邀请了赋能工业数字化技术创新的多位合作伙伴&#xff0c;展示当前中国工业物联网领域的优秀技术与成果&#xff0c;共聚一堂积极探讨数字化机器视觉、控制…

【Maven】SpringBoot多模块项目利用reversion占位符,进行版本管理.打包时版本号不能识别问题

问题原因&#xff1a; 多模块项目使用reversion点位符进行版管理&#xff0c;打包时生成的pom文件未将 {reversion}占位符替换为真实版本号。 而当子模块被依赖时&#xff0c;引入的pom文件中版本号是&#xff1a;{reversion}。而根据这个版本号去找相应父模块时肯定是找不到的…

了解:组件和组件的值的分享

<template><Block title"热门公司"><div slot"content" class"container"><CompanyList :company-list"currentPageCompany"></CompanyList><div class"pagination"><el-pagination…

十四、MySql的用户管理

文章目录 一、用户管理二、用户&#xff08;一&#xff09;用户信息&#xff08;二&#xff09;创建用户1.语法&#xff1a;2.案例&#xff1a; &#xff08;三&#xff09; 删除用户1.语法&#xff1a;2.示例&#xff1a; &#xff08;四&#xff09;修改用户密码1.语法&#…

【LeetCode热题100】接雨水+无重复字符的最长子串+找到字符串中所有字母异位词

42.接雨水 思路&#xff1a; 按照列计算 每列的宽度是1 所以每列承接雨水即为雨水的高度 这一列高度通过看图计算我们可以得到hmin(lh,rh)-h[i] lh是这一列左侧最高柱子的高度&#xff0c;rh为这一列右侧最高柱子的高度 当遇到第一个和最后一个时我们不计算雨水&#xff08;装…

11:STM32---spl通信

目录 一:SPL通信 1:简历 2:硬件电路 3:移动数据图 4:SPI时序基本单元 A : 开/ 终条件 B:SPI时序基本单元 A:模式0 B:模式1 C:模式2 D:模式3 C:SPl时序 A:发送指令 B: 指定地址写 C:指定地址读 二: W25Q64 1:简历 2: 硬件电路 3:W25Q64框图 4: Flash操作注意…