SpringBoot之控制器的返回值处理方式

 更新时间:2023年07月19日 08:37:07   作者:yyangqqian  
这篇文章主要介绍了SpringBoot之控制器的返回值处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

SpringBoot控制器的返回值处理

  • @Controller:默认返回值是视图名称,如果需要返回Json字符串,需要在方法上加@ResponseBody注解,默认使用 Jackson 框架处理。
  • @RestController:是@ResponseBody和@Controller的组合注解。

Spring Boot 中默认使用的 Json 解析框架是 Jackson 。

在实际项目中,难免会遇到一些 null 值出现,在转 Json 时,是不希望有这些 null 出现的。

比如期望所有的 null 在转 Json 时都变成 “” 这种空字符串。

在 Spring Boot 中,做一下配置即可,新建一个 Jackson 的配置类:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.io.IOException;
@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }
}

SpringBoot 启用Fastjson转换

fastJson依赖导入:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.35</version>
</dependency>

SpringBoot 启用Fastjson转换,需要继承WebMvcConfigurerAdapter,并重写configureMessageConverters方法。

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class FastJWebMvcConfigurer extends WebMvcConfigurationSupport {
    /***
     * 使用阿里 FastJson 作为JSON MessageConverter
     * @param converters
     * */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
                // 保留map空的字段
                SerializerFeature.WriteMapNullValue,
                // 将String类型的null转成""
                SerializerFeature.WriteNullStringAsEmpty,
                // 将Number类型的null转成0
                SerializerFeature.WriteNullNumberAsZero,
                // 将List类型的null转成[]
                SerializerFeature.WriteNullListAsEmpty,
                // 将Boolean类型的null转成false
                SerializerFeature.WriteNullBooleanAsFalse,
                // 避免循环引用
                SerializerFeature.DisableCircularReferenceDetect);
        // converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        List<MediaType> mediaTypeList = new ArrayList<>();
        // 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces = "application/json"
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }
}

SpringBoot控制器返回值-中文乱码问题

@RequestMapping 注解增加produces属性解决中文乱码问题

@RequestMapping(value="/create/index",produces = "application/json;charset=utf-8")
public ResponseBean createIndex(@RequestParam String indexName)
        {
        try {
        XContentBuilder builder = XContentFactory.jsonBuilder()
        .startObject()
        .field("properties")
        .startObject()
        .field("name").startObject().field("index", "true").field("type", "keyword").endObject()
        .field("age").startObject().field("index", "true").field("type", "integer").endObject()
        .field("money").startObject().field("index", "true").field("type", "double").endObject()
        .field("address").startObject().field("index", "true").field("type", "text").endObject()
        .field("birthday").startObject().field("index", "true").field("type", "date").endObject()
//.field("address").startObject().field("index", "true").field("type", "text").field("analyzer", "ik_max_word").endObject()
//.field("birthday").startObject().field("index", "true").field("type", "date").field("format", "strict_date_optional_time||epoch_millis").endObject()
        .endObject()
        .endObject();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);
        createIndexRequest.mapping(indexName,builder);
        CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        boolean acknowledged = createIndexResponse.isAcknowledged();
        if (acknowledged) {
        return new ResponseBean(200, "创建成功", null);
        } else {
        return new ResponseBean(1002, "创建失败", null);
        }
        } catch (IOException e) {
        e.printStackTrace();
        }catch (ElasticsearchStatusException e)
        {
        logger.info("创建失败---索引已经存在");
        return new ResponseBean(1002, "创建失败---索引已经存在", null);
        }
        return null;
        }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Java实现微信公众号自定义菜单的创建方法示例

    Java实现微信公众号自定义菜单的创建方法示例

    这篇文章主要介绍了Java实现微信公众号自定义菜单的创建方法,结合实例形式分析了java创建微信公众号自定义菜单的具体步骤、实现方法及相关操作注意事项,需要的朋友可以参考下
    2019-10-10
  • Go Java 算法之迷你语法分析器示例详解

    Go Java 算法之迷你语法分析器示例详解

    这篇文章主要为大家介绍了Go Java 算法之迷你语法分析器示例详解,
    有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • 一文搞懂Mybatis-plus的分页查询操作

    一文搞懂Mybatis-plus的分页查询操作

    说起分页机制,相信我们程序员都不陌生,今天,我就给大家分享一下Mybatis-plus的分页机制,供大家学习和Copy,感兴趣的可以了解一下
    2022-06-06
  • 详解在Spring中如何自动创建代理

    详解在Spring中如何自动创建代理

    这篇文章主要介绍了详解在Spring中如何自动创建代理,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • 详解springcloud组件consul服务治理

    详解springcloud组件consul服务治理

    Consul是一款由HashiCorp公司开源的,用于服务治理的软件,Spring Cloud Consul对其进行了封装,这篇文章主要介绍了springcloud组件consul服务治理,需要的朋友可以参考下
    2022-08-08
  • Java生成动态版验证码的方法实例

    Java生成动态版验证码的方法实例

    这篇文章主要给大家介绍了利用Java生成动态版验证码的方法实例,本文生成的是GIF格式 + 干扰元素,让验证码破解难度又上了一个层次,文中给出了详细的示例代码,并在文末给出了完整的实例代码供大家下载学习,需要的朋友们下面来一起看看吧。
    2017-04-04
  • JavaAgent实现http接口发布方式浅析

    JavaAgent实现http接口发布方式浅析

    这篇文章主要介绍了JavaAgent实现http接口发布方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习吧
    2023-03-03
  • Zookeeper全局唯一ID生成方案解析

    Zookeeper全局唯一ID生成方案解析

    这篇文章主要介绍了Zookeeper全局唯一ID生成方案解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-12-12
  • Java中Date日期时间类具体使用

    Java中Date日期时间类具体使用

    本文主要介绍了Java中Date日期时间类具体使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-04-04
  • SpringBoot整合Echarts实现用户人数和性别展示功能(详细步骤)

    SpringBoot整合Echarts实现用户人数和性别展示功能(详细步骤)

    这篇文章主要介绍了SpringBoot整合Echarts实现用户人数和性别展示,通过数据库设计、实现数据访问层、业务逻辑层和控制层的代码编写,以及前端页面的开发,本文详细地介绍了SpringBoot整合Echarts的实现步骤和代码,需要的朋友可以参考下
    2023-05-05

最新评论