SpringBoot整合Web開發(fā)之Json數(shù)據(jù)返回的實現(xiàn)
本章概要
- 返回JSON數(shù)據(jù)
- 靜態(tài)資源訪問
返回JSON數(shù)據(jù)
默認(rèn)實現(xiàn)
JSON 是目前主流的前后端數(shù)據(jù)傳輸方式,Spring MVC中使用消息轉(zhuǎn)換器HTTPMessageConverter對JSON的轉(zhuǎn)換提供了很好的支持,在Spring Boot中更進一步,對相關(guān)配置做了進一步的簡化。默認(rèn)情況下,創(chuàng)建一個Spring Boot項目后,添加Web依賴,代碼如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
這個依賴中默認(rèn)加入了jackson-databind 作為JSON處理器,此時不需要添加額外的JSON處理器就能返回一段JSON了。創(chuàng)建一個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; } }
然后創(chuàng)建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; } }
當(dāng)然,如果需要頻繁地用到@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數(shù)據(jù),如圖:
這是Spring Boot 自帶的處理方式。如果采用這種方式,那么對于字段忽略、日期格式化等常見需求都可以通過注解來解決。這是通過Spring 中默認(rèn)提供的 MappingJackson2HttpMessageConverter 來實現(xiàn)的,當(dāng)然也可以根據(jù)需求自定義轉(zhuǎn)換器。
自定義轉(zhuǎn)換器
常見的JSON 處理器除了jsckson-databind之外,還有Gson 和 fastjson ,針對常見用法來舉例。
1. 使用Gson
Gson是 Goole 的一個開源JSON解析框架。使用Gson,需要先去處默認(rèn)的jackson-databind,然后引入Gson依賴,代碼如下:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <!-- 排除默認(rèn)的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 中默認(rèn)提供了Gson的自動轉(zhuǎn)換類 GsonHttpMessageConvertersConfiguration,因此Gson的依賴添加成功后,可以像使用jackson-databind 那樣直接使用Gson。但在Gson進行轉(zhuǎn)換是,如果想對日期數(shù)據(jù)進行格式化,那么還需要開發(fā)者自定義HTTPMessageConverter。先看 GsonHttpMessageConvertersConfiguration 中的一段代碼:
@Bean @ConditionalOnMissingBean public GsonHttpMessageConverter gsonHttpMessageConverter(Gson gson) { GsonHttpMessageConverter converter = new GsonHttpMessageConverter(); converter.setGson(gson); return converter; }
@ConditionalOnMissingBean 注解標(biāo)識當(dāng)前項目中沒有提供 GsonHttpMessageConverter 時才會使用默認(rèn)的 GsonHttpMessageConverter ,所以開發(fā)者只需要提供一個 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; } }
代碼解釋:
- 開發(fā)者自己提供一個GsonHttpMessageConverter 的實例
- 設(shè)置Gson解析日期的格式
- 設(shè)置Gson解析是修飾符為 protected 的字段被過濾掉
- 創(chuàng)建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",查看返回結(jié)果,如圖:
2. 使用fastjson
fastjson是阿里巴巴的一個開源 JSON 解析框架,是目前 JSON 解析速度最快的開源框架,該框架也可以集成到 Spring Boot 中。不同于Gson,fastjson集成完成之后并不能立馬使用,需要開發(fā)者提供相應(yīng)的 HttpMessageConverter 后才能使用,集成fastjson需要先除去jackson-databind 依賴,引入fastjson 依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <!-- 排除默認(rèn)的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解析過程的一些細(xì)節(jié),例如日期格式、數(shù)據(jù)編碼、是否在生成的JSON中輸出類名、是否輸出value為null的數(shù)據(jù)、生成的JSON格式化、空集合輸出[]而非null、空字符串輸出""而非null等基本配置
還需要配置一下響應(yīng)編碼,否則會出現(xiàn)亂碼的情況,在application.properties 中添加如下配置:
# 是否強制對HTTP響應(yīng)上配置的字符集進行編碼。
spring.http.encoding.force-response=true
BookController 跟 使用Gson的 BookController 一致即可,此時在瀏覽器中輸入"http://localhost:8081/book",查看返回結(jié)果,如圖:
對于 FastJsonHttpMessageConverter 的配置,除了上邊這種方式之外,還有另一種方式。
在Spring Boot 項目中,當(dāng)開發(fā)者引入 spring-boot-starter-web 依賴后,該依賴又依賴了 spring-boot-autoconfigure , 在這個自動化配置中,有一個 WebMvcAutoConfiguration 類提供了對 Spring MVC 最進本的配置,如果某一項自動化配置不滿足開發(fā)需求,開發(fā)者可以針對該項自定義配置,只需要實現(xiàn) WebMvcConfig 接口即可(在Spring Boot 5.0 之前是通過繼承 WebMvcConfigurerAdapter 來實現(xiàn)的),代碼如下:
@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 類實現(xiàn) WebMvcConfigurer 接口中的 configureMessageConverters 方法
- 將自定義的 FastJsonHttpMessageConverter 加入 converter 中
注意:如果使用了Gson , 也可以采用這種方式配置,但是不推薦。因為當(dāng)項目中沒有 GsonHttpMessageConverter 時,Spring Boot 會自己提供一個 GsonHttpMessageConverter ,此時重寫 configureMessageConverters 方法,參數(shù) converters 中已經(jīng)有 GsonHttpMessageConverter 的實例了,需要替換已有的 GsonHttpMessageConverter 實例,操作比較麻煩,所以對于Gson,推薦直接提供 GsonHttpMessageConverter 。
靜態(tài)資源訪問
在Spring MVC 中,對于靜態(tài)資源都需要開發(fā)者手動配置靜態(tài)資源過濾。Spring Boot 中對此也提供了自動化配置,可以簡化靜態(tài)資源過濾配置。
默認(rèn)策略
Spring Boot 中對于Spring MVC 的自動化配置都在 WebMvcAutoConfiguration 類中,因此對于默認(rèn)的靜態(tài)資源過濾策略可以從這個類中一窺究竟。
在 WebMvcAutoConfiguration 類中有一個靜態(tài)內(nèi)部類 WebMvcAutoConfigurationAdapter ,實現(xiàn)了 WebMvcConfigurer 接口。WebMvcConfigurer 接口中有一個方法 addResourceHandlers 是用來配置靜態(tài)資源過濾的。方法在 WebMvcAutoConfigurationAdapter 類中得到了實現(xiàn),源碼如下:
@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 在這里進行了默認(rèn)的靜態(tài)資源過濾配置,其中 staticPathPattern 默認(rèn)定義在 WebMvcProperties 中,定義內(nèi)容如下:
/** * Path pattern used for static resources. */ private String staticPathPattern = "/**";
this.resourceProperties.getStaticLocations() 獲取到的默認(rèn)靜態(tài)資源位置定義在 ResourceProperties 中,代碼如下:
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
在 getResourceLocations 方法中,對這4個靜態(tài)資源位置做了擴充,代碼如下:
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 默認(rèn)會過濾所有的靜態(tài)資源,而靜態(tài)資源的位置一共有5個,分別是"classpath:/META-INF/resources/“、“classpath:/resources/”、“classpath:/static/”、“classpath:/public/”、”/“,一般情況下Spring Boot 項目不需要webapp目錄,所以第5個”/"可以暫時不考慮。剩下4個路徑加載的優(yōu)先級如下:
如果開發(fā)者使用IDEA創(chuàng)建Spring Boot 項目,就會默認(rèn)創(chuàng)建出 classpath:/static/ 目錄,靜態(tài)資源一般放在這個目錄即可。重啟項目,訪問瀏覽器"http://localhost:8081/p1.jpg",即可訪問靜態(tài)資源。
自定義策略
1. 在配置文件中定義
在application.properties中直接定義過濾規(guī)則和靜態(tài)資源位置,如下:
# 靜態(tài)資源過濾規(guī)則
spring.mvc.static-path-pattern=/staticFile/**
# 靜態(tài)資源位置
spring.resources.static-locations=classpath:/staticFile/
在resources目錄下新建目錄 staticFile,放入文件, 重啟項目,訪問瀏覽器"http://localhost:8081/staticFile/p1.jpg",即可訪問靜態(tài)資源。此時再次訪問"http://localhost:8081/p1.jpg"會提示 404
2. Java編碼定義
實現(xiàn) WebMvcConfigurer 接口即可,然后覆蓋接口的 addResourceHandlers 方法,如下:
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry){ registry.addResourceHandler("/staticFile/**").addResourceLocations("classpath:/staticFile/"); } }
到此這篇關(guān)于SpringBoot整合Web開發(fā)之Json數(shù)據(jù)返回的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot Json數(shù)據(jù)返回內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一文搞懂java中類及static關(guān)鍵字執(zhí)行順序
這篇文章主要介紹了一文搞懂java中類及static關(guān)鍵字執(zhí)行順序,文章通過類的生命周期展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09springboot中Getmapping獲取參數(shù)的實現(xiàn)方式
這篇文章主要介紹了springboot中Getmapping獲取參數(shù)的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05基于SpringBoot+vue實現(xiàn)前后端數(shù)據(jù)加解密
這篇文章主要給大家介紹了基于SpringBoot+vue實現(xiàn)前后端數(shù)據(jù)加解密,文中有詳細(xì)的示例代碼,具有一定的參考價值,感興趣的小伙伴可以自己動手試一試2023-08-08