最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合Web開發(fā)之Json數(shù)據(jù)返回的實現(xiàn)

 更新時間:2022年08月15日 08:51:52   作者:一只小熊貓呀  
這篇文章主要介紹了SpringBoot整合Web開發(fā)其中Json數(shù)據(jù)返回的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

本章概要

  • 返回JSON數(shù)據(jù)
  • 靜態(tài)資源訪問

返回JSON數(shù)據(jù)

默認實現(xiàn)

JSON 是目前主流的前后端數(shù)據(jù)傳輸方式,Spring MVC中使用消息轉(zhuǎn)換器HTTPMessageConverter對JSON的轉(zhuǎn)換提供了很好的支持,在Spring Boot中更進一步,對相關(guān)配置做了進一步的簡化。默認情況下,創(chuàng)建一個Spring Boot項目后,添加Web依賴,代碼如下:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>

這個依賴中默認加入了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;
    }
}

當然,如果需要頻繁地用到@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 中默認提供的 MappingJackson2HttpMessageConverter 來實現(xiàn)的,當然也可以根據(jù)需求自定義轉(zhuǎn)換器。

自定義轉(zhuǎn)換器

常見的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的自動轉(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 注解標識當前項目中沒有提供 GsonHttpMessageConverter 時才會使用默認的 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 的實例
  • 設置Gson解析日期的格式
  • 設置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ā)者提供相應的 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解析過程的一些細節(jié),例如日期格式、數(shù)據(jù)編碼、是否在生成的JSON中輸出類名、是否輸出value為null的數(shù)據(jù)、生成的JSON格式化、空集合輸出[]而非null、空字符串輸出""而非null等基本配置

還需要配置一下響應編碼,否則會出現(xiàn)亂碼的情況,在application.properties 中添加如下配置:

# 是否強制對HTTP響應上配置的字符集進行編碼。
spring.http.encoding.force-response=true

BookController 跟 使用Gson的 BookController 一致即可,此時在瀏覽器中輸入"http://localhost:8081/book",查看返回結(jié)果,如圖:

對于 FastJsonHttpMessageConverter 的配置,除了上邊這種方式之外,還有另一種方式。

在Spring Boot 項目中,當開發(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 , 也可以采用這種方式配置,但是不推薦。因為當項目中沒有 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)資源過濾配置。

默認策略

Spring Boot 中對于Spring MVC 的自動化配置都在 WebMvcAutoConfiguration 類中,因此對于默認的靜態(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 在這里進行了默認的靜態(tài)資源過濾配置,其中 staticPathPattern 默認定義在 WebMvcProperties 中,定義內(nèi)容如下:

/**
 * Path pattern used for static resources.
 */
private String staticPathPattern = "/**";

this.resourceProperties.getStaticLocations() 獲取到的默認靜態(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 默認會過濾所有的靜態(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 項目,就會默認創(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)文章

  • 利用Spring MVC+Mybatis實現(xiàn)Mysql分頁數(shù)據(jù)查詢的過程詳解

    利用Spring MVC+Mybatis實現(xiàn)Mysql分頁數(shù)據(jù)查詢的過程詳解

    這篇文章主要給大家介紹了關(guān)于利用Spring MVC+Mybatis實現(xiàn)Mysql分頁數(shù)據(jù)查詢的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。
    2017-08-08
  • 配置DispatcherServlet的方法介紹

    配置DispatcherServlet的方法介紹

    今天小編就為大家分享一篇關(guān)于配置DispatcherServlet的方法介紹,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-01-01
  • Java Web基于Session的登錄實現(xiàn)方法

    Java Web基于Session的登錄實現(xiàn)方法

    這篇文章主要介紹了Java Web基于Session的登錄實現(xiàn)方法,涉及Java針對session的操作及表單提交與驗證技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-10-10
  • SpringBoot自動配置深入探究實現(xiàn)原理

    SpringBoot自動配置深入探究實現(xiàn)原理

    在springboot的啟動類中可以看到@SpringBootApplication注解,它是SpringBoot的核心注解,也是一個組合注解。其中@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三個注解尤為重要。今天我們就來淺析這三個注解的含義
    2022-08-08
  • SpringMVC使用MultipartFile 實現(xiàn)異步上傳方法介紹

    SpringMVC使用MultipartFile 實現(xiàn)異步上傳方法介紹

    這篇文章主要介紹了SpringMVC使用MultipartFile 實現(xiàn)異步上傳方法介紹,涉及pom依賴的添加,配置文件的修改等具體操作代碼,需要的朋友可以了解下。
    2017-09-09
  • Java利用棧實現(xiàn)簡易計算器功能

    Java利用棧實現(xiàn)簡易計算器功能

    這篇文章主要為大家詳細介紹了Java利用棧實現(xiàn)簡易計算器功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • IDEA GIT 忽略文件的最佳方式推薦

    IDEA GIT 忽略文件的最佳方式推薦

    這篇文章主要介紹了IDEA GIT 忽略文件的最佳方式推薦,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-01-01
  • SpringBoot中的數(shù)據(jù)脫敏處理詳解

    SpringBoot中的數(shù)據(jù)脫敏處理詳解

    本文介紹了在SpringBoot中進行數(shù)據(jù)脫敏處理的方法,通過自定義注解和Jackson配置,可以輕松實現(xiàn)對敏感數(shù)據(jù)的脫敏,保護用戶隱私
    2025-03-03
  • Java日常練習題,每天進步一點點(46)

    Java日常練習題,每天進步一點點(46)

    下面小編就為大家?guī)硪黄狫ava基礎的幾道練習題(分享)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧,希望可以幫到你
    2021-08-08
  • 詳述IntelliJ IDEA 中自動生成 serialVersionUID 的方法(圖文)

    詳述IntelliJ IDEA 中自動生成 serialVersionUID 的方法(圖文)

    本篇文章主要介紹了詳述IntelliJ IDEA 中自動生成 serialVersionUID 的方法(圖文),具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-11-11

最新評論

双辽市| 石河子市| 三原县| 延长县| 濮阳县| 若尔盖县| 公主岭市| 苍梧县| 民和| 饶河县| 连州市| 保靖县| 惠东县| 北流市| 进贤县| 高青县| 清镇市| 泌阳县| 上饶市| 德清县| 舟山市| 昌图县| 彩票| 乌拉特后旗| 越西县| 楚雄市| 乐至县| 黎平县| 柳江县| 东乌珠穆沁旗| 延吉市| 阿拉善盟| 嵊泗县| 阜康市| 比如县| 高唐县| 库伦旗| 电白县| 绥化市| 大宁县| 浏阳市|