SpringBoot整合Web开发之Json数据返回的实现
作者:一只小熊猫呀 发布时间:2023-04-27 05:06:51
本章概要
返回JSON数据
静态资源访问
返回JSON数据
默认实现
JSON 是目前主流的前后端数据传输方式,Spring MVC中使用消息转换器HTTPMessageConverter对JSON的转换提供了很好的支持,在Spring Boot中更进一步,对相关配置做了进一步的简化。默认情况下,创建一个Spring Boot项目后,添加Web依赖,代码如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
这个依赖中默认加入了jackson-databind 作为JSON处理器,此时不需要添加额外的JSON处理器就能返回一段JSON了。创建一个Book实体类:
public class Book {
private int id;
private String name;
private String author;
@JsonIgnore
private Float price;
@JsonFormat(pattern = "yyyy-MM-dd")
private Date publicationDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Date getPublicationDate() {
return publicationDate;
}
public void setPublicationDate(Date publicationDate) {
this.publicationDate = publicationDate;
}
}
然后创建BookController,返回Book对象即可:
@Controller
public class BookController {
@GetMapping(value = "/book")
@ResponseBody
public Book books(){
Book b1 = new Book();
b1.setId(1);
b1.setAuthor("唐家三少");
b1.setName("斗罗大陆Ⅰ");
b1.setPrice(60f);
b1.setPublicationDate(new Date());
return b1;
}
}
当然,如果需要频繁地用到@ResponseBody 注解,那么可以采用@RestController 组合注解代替@Controller和@ResponseBody ,代码如下:
@RestController
public class BookController {
@GetMapping(value = "/book")
public Book books(){
Book b1 = new Book();
b1.setId(1);
b1.setAuthor("唐家三少");
b1.setName("斗罗大陆Ⅰ");
b1.setPrice(60f);
b1.setPublicationDate(new Date());
return b1;
}
}
此时在浏览器中输入"http://localhost:8081/book",即可看到返回了JSON数据,如图:
这是Spring Boot 自带的处理方式。如果采用这种方式,那么对于字段忽略、日期格式化等常见需求都可以通过注解来解决。这是通过Spring 中默认提供的 MappingJackson2HttpMessageConverter 来实现的,当然也可以根据需求自定义转换器。
自定义转换器
常见的JSON 处理器除了jsckson-databind之外,还有Gson 和 fastjson ,针对常见用法来举例。
1. 使用Gson
Gson是 Goole 的一个开源JSON解析框架。使用Gson,需要先去处默认的jackson-databind,然后引入Gson依赖,代码如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 排除默认的jackson-databind -->
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入Gson依赖 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
由于Spring Boot 中默认提供了Gson的自动转换类 GsonHttpMessageConvertersConfiguration,因此Gson的依赖添加成功后,可以像使用jackson-databind 那样直接使用Gson。但在Gson进行转换是,如果想对日期数据进行格式化,那么还需要开发者自定义HTTPMessageConverter。先看 GsonHttpMessageConvertersConfiguration 中的一段代码:
@Bean
@ConditionalOnMissingBean
public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) {
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(gson);
return converter;
}
@ConditionalOnMissingBean 注解标识当前项目中没有提供 GsonHttpMessageConverter 时才会使用默认的 GsonHttpMessageConverter ,所以开发者只需要提供一个 GsonHttpMessageConverter 即可,代码如下:
@Configuration
public class GsonConfig {
@Bean
GsonHttpMessageConverter gsonHttpMessageConverter(){
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("yyyy-MM-dd");
builder.excludeFieldsWithModifiers(Modifier.PROTECTED);
Gson gson = builder.create();
gsonHttpMessageConverter.setGson(gson);
return gsonHttpMessageConverter;
}
}
代码解释:
开发者自己提供一个GsonHttpMessageConverter 的实例
设置Gson解析日期的格式
设置Gson解析是修饰符为 protected 的字段被过滤掉
创建Gson对象放入GsonHttpMessageConverter 的实例中并返回
此时,将Book类中的price字段的修饰符改为 protected ,去掉注解,代码如下:
public class Book {
private int id;
private String name;
private String author;
protected Float price;
private Date publicationDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public Date getPublicationDate() {
return publicationDate;
}
public void setPublicationDate(Date publicationDate) {
this.publicationDate = publicationDate;
}
}
此时在浏览器中输入"http://localhost:8081/book",查看返回结果,如图:
2. 使用fastjson
fastjson是阿里巴巴的一个开源 JSON 解析框架,是目前 JSON 解析速度最快的开源框架,该框架也可以集成到 Spring Boot 中。不同于Gson,fastjson集成完成之后并不能立马使用,需要开发者提供相应的 HttpMessageConverter 后才能使用,集成fastjson需要先除去jackson-databind 依赖,引入fastjson 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- 排除默认的jackson-databind -->
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 引入fastjson依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
然后配置fastjson 的 HttpMessageConverter :
@Configuration
public class MyFastJsonConfig {
@Bean
FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd");
fastJsonConfig.setCharset(Charset.forName("UTF-8"));
fastJsonConfig.setSerializerFeatures(
SerializerFeature.WriteClassName,
SerializerFeature.WriteMapNullValue,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty
);
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
return fastJsonHttpMessageConverter;
}
}
代码解释:
自定义 MyFastJsonConfig 完成对 FastJsonHttpMessageConverter Bean的提供
配置JSON解析过程的一些细节,例如日期格式、数据编码、是否在生成的JSON中输出类名、是否输出value为null的数据、生成的JSON格式化、空集合输出[]而非null、空字符串输出""而非null等基本配置
还需要配置一下响应编码,否则会出现乱码的情况,在application.properties 中添加如下配置:
# 是否强制对HTTP响应上配置的字符集进行编码。
spring.http.encoding.force-response=true
BookController 跟 使用Gson的 BookController 一致即可,此时在浏览器中输入"http://localhost:8081/book",查看返回结果,如图:
对于 FastJsonHttpMessageConverter 的配置,除了上边这种方式之外,还有另一种方式。
在Spring Boot 项目中,当开发者引入 spring-boot-starter-web 依赖后,该依赖又依赖了 spring-boot-autoconfigure , 在这个自动化配置中,有一个 WebMvcAutoConfiguration 类提供了对 Spring MVC 最进本的配置,如果某一项自动化配置不满足开发需求,开发者可以针对该项自定义配置,只需要实现 WebMvcConfig 接口即可(在Spring Boot 5.0 之前是通过继承 WebMvcConfigurerAdapter 来实现的),代码如下:
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setDateFormat("yyyy-MM-dd");
config.setCharset(Charset.forName("UTF-8"));
config.setSerializerFeatures(
SerializerFeature.WriteClassName,
SerializerFeature.WriteMapNullValue,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty
);
converter.setFastJsonConfig(config);
converters.add(converter);
}
}
代码解释:
自定义 MyWebMvcConfig 类实现 WebMvcConfigurer 接口中的 configureMessageConverters 方法
将自定义的 FastJsonHttpMessageConverter 加入 converter 中
注意:如果使用了Gson , 也可以采用这种方式配置,但是不推荐。因为当项目中没有 GsonHttpMessageConverter 时,Spring Boot 会自己提供一个 GsonHttpMessageConverter ,此时重写 configureMessageConverters 方法,参数 converters 中已经有 GsonHttpMessageConverter 的实例了,需要替换已有的 GsonHttpMessageConverter 实例,操作比较麻烦,所以对于Gson,推荐直接提供 GsonHttpMessageConverter 。
静态资源访问
在Spring MVC 中,对于静态资源都需要开发者手动配置静态资源过滤。Spring Boot 中对此也提供了自动化配置,可以简化静态资源过滤配置。
默认策略
Spring Boot 中对于Spring MVC 的自动化配置都在 WebMvcAutoConfiguration 类中,因此对于默认的静态资源过滤策略可以从这个类中一窥究竟。
在 WebMvcAutoConfiguration 类中有一个静态内部类 WebMvcAutoConfigurationAdapter ,实现了 WebMvcConfigurer 接口。WebMvcConfigurer 接口中有一个方法 addResourceHandlers 是用来配置静态资源过滤的。方法在 WebMvcAutoConfigurationAdapter 类中得到了实现,源码如下:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
...
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(
registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(
this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod))
.setCacheControl(cacheControl));
}
}
Spring Boot 在这里进行了默认的静态资源过滤配置,其中 staticPathPattern 默认定义在 WebMvcProperties 中,定义内容如下:
/**
* Path pattern used for static resources.
*/
private String staticPathPattern = "/**";
this.resourceProperties.getStaticLocations() 获取到的默认静态资源位置定义在 ResourceProperties 中,代码如下:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/" };
在 getResourceLocations 方法中,对这4个静态资源位置做了扩充,代码如下:
static String[] getResourceLocations(String[] staticLocations) {
String[] locations = new String[staticLocations.length
+ SERVLET_LOCATIONS.length];
System.arraycopy(staticLocations, 0, locations, 0, staticLocations.length);
System.arraycopy(SERVLET_LOCATIONS, 0, locations, staticLocations.length,
SERVLET_LOCATIONS.length);
return locations;
}
其中 SERVLET_LOCATIONS 的定义是一个{ “/” }。
综上可以看到,Spring Boot 默认会过滤所有的静态资源,而静态资源的位置一共有5个,分别是"classpath:/META-INF/resources/“、“classpath:/resources/”、“classpath:/static/”、“classpath:/public/”、”/“,一般情况下Spring Boot 项目不需要webapp目录,所以第5个”/"可以暂时不考虑。剩下4个路径加载的优先级如下:
如果开发者使用IDEA创建Spring Boot 项目,就会默认创建出 classpath:/static/ 目录,静态资源一般放在这个目录即可。重启项目,访问浏览器"http://localhost:8081/p1.jpg",即可访问静态资源。
自定义策略
1. 在配置文件中定义
在application.properties中直接定义过滤规则和静态资源位置,如下:
# 静态资源过滤规则
spring.mvc.static-path-pattern=/staticFile/**
# 静态资源位置
spring.resources.static-locations=classpath:/staticFile/
在resources目录下新建目录 staticFile,放入文件, 重启项目,访问浏览器"http://localhost:8081/staticFile/p1.jpg",即可访问静态资源。此时再次访问"http://localhost:8081/p1.jpg"会提示 404
2. Java编码定义
实现 WebMvcConfigurer 接口即可,然后覆盖接口的 addResourceHandlers 方法,如下:
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/staticFile/**").addResourceLocations("classpath:/staticFile/");
}
}
来源:https://blog.csdn.net/GXL_1012/article/details/125897670
猜你喜欢
- 一直使用Eclipse环境开发Android,也尝鲜使用过Android Studio去开发,各种IDE配合Android SDK及SDK原
- 背景传说里玉皇大帝派龙王马上降雨到共光一带,龙王接到玉皇大帝命令,立马从海上调水,跑去共光施云布雨,但粗心又着急的龙王不小心把海里的鲸鱼随着
- Spring Data Jpa复杂查询总结只是做一个总结所以就不多说废话了实体类@Entity@Table(name = "t_h
- 目录第一种方式第二种方式第三种方式第四种方式(缺点:将所有的数字类型都会转为字符串)web项目中,Java后端传过来的Long/long类型
- 将JavaDoc 注释 生成API文档1. 打开java代码,编写JavaDoc 注释,只有按照java的规范编写注释,才能很好的生成API
- Java程序设计 图形用户界面 【十】复选框复选框JCheckBoxJCheckBox类方法作用public JCheckBox(Icon
- 第1部分 ArrayList介绍ArrayList简介ArrayList 是一个数组队列,相当于 动态数组。与Java中的数组相比,它的容量
- java缓冲流本身不具IO功能,只是在别的流上加上缓冲提高效率,像是为别的流装上一种包装。当对文件或其他目标频繁读写或操作效率低,效能差。这
- 通过子类调用父类的变量,有两种方法:1、把父类的变量设置成public:package triangle.opengl.wlz.stu.ch
- 一、基本使用它们是 LockSupport 类中的方法// 暂停当前线程LockSupport.park(); // 恢复某个线程的运行Lo
- 前段时间写了一篇基于mybatis实现的多数据源博客。感觉不是很好,这次打算加入git,来搭建一个基于Mybatis-Plus的多数据源项目
- 由于工作中 使用 MultipartFile 与现有的一些上传文件组件冲突所以使用其他的接收上传文件的方法.首先我把 M
- 一、一级缓存二级缓存的概念解释(1)一级缓存就是Session级别的缓存,一个Session做了一个查询操作,它会把这个操作的结果放在一级缓
- (注意:本文基于JDK1.8)前言元素在存储到内存中,当我们需要使用在内存中存储的元素,这就涉及到在内存中查找元素,今天一起学习Vector
- Springboot 在普通类型注入Service或mapper最近遇到一个难题(大佬可能感觉这太简单了把),对于我这样的小白来说,确实有些
- 前言 因为自己在做的一个小软件里面需要用到从A-Z排序的ListView,所以自然而然的想到了微信的联系人,我想要的就是那样的效果。本来没
- 关于java图片验证码的文章最近更新了不少,帮助大家掌握java验证码的生成技术,下文为大家分享了java生成图片验证码最简单的方法,供大家
- 本文实例为大家分享了java使用字符画一个海绵宝宝的具体代码,供大家参考,具体内容如下用字符画一个海绵宝宝用" &ldqu
- 查询返回Map<String,Object>类型mybatis 查询返回Map<String,Object> 类型,
- 引言最近,各大平台都新增了评论区显示发言者ip归属地的功能,例如哔哩哔哩,微博,知乎等等。Java 中是如何获取 IP&