SpringBoot之控制器的返回值处理方式
作者: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; }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。