SpringBoot學習筆記(一)——SpringBoot概要與快速入門


 一、Spring Boot概要

沒有Spring Boot開發項目時各框架間的集成(如SSM)非常繁瑣,兼容性問題處理麻煩,開發效率低。

1.1、Spring Boot 簡介

使用 Spring Boot 可以很容易地創建出能直接運行的獨立的、生產級別的基於 Spring 的應用。我們對 Spring 平台和第三方類庫有自己的考慮,因此您可以從最基本的開始。大多數 Spring Boot 應用只需要很少的 Spring 配置。

您可以使用 Spring Boot 來創建一個可以使用 java -jar 命令來運行或者基於傳統的 war 包部署的應用程序。我們還提供了一個用於運行 spring scripts 的命令行工具。

我們的主要目標是:

  • 為所有 Spring Boot 開發提供一個更快、更全面的入門體驗。
  • 堅持自我雖好,但當需求出現偏離,您需要能迅速擺脫出來。
  • 提供大量非功能性特性相關項目(例如:內嵌服務器、安全、指標、健康檢查、外部配置)。
  • 絕對沒有代碼生成,也不要求 XML 配置。

SpringBoot提供了一種快速使用Spring的方式,基於約定優於配置的思想,可以讓開發人員不必在配置與邏輯業務之間進行思維的切換,全身心的投入到邏輯業務的代碼編寫中,從而大大提高了開發的效率,一定程度上縮短了項目周期。2014 年 4 月,Spring Boot 1.0.0 發布。Spring的頂級項目之一(https://spring.io)。

1.2、Spring Boot特性

Spring Boot包含以下幾個特性:

(1)、默認提供了大部分框架的使用方式,方便進行快速集

(2)、Spring Boot應用可以獨立運行,符合微服務的開發理念

(3)、Spring Boot內置WEB容器,無需部署WAR包即可運行

(4)、提供了各種生產就緒型功能,如指標,健康檢查和外部配置

(5)、Spring Boot通過網站提供了項目模板,方便項目的初始化

Spring Boot 兼容 Apache Maven 3.2 或更高版本。如果您還沒有安裝 Maven,可以到 maven.apache.org

您可以跟使用任何標准 Java 庫的方式一樣使用 Spring Boot。只需要在 classpath 下包含相應的 spring-boot-*.jar 文件即可。Spring Boot 不需要任何專用的工具來集成,因此您可以使用任何 IDE 或者文本編輯器,並且 Spring Boot 應用也沒什么特殊之處,因此可以像任何其它 Java 程序一樣運行和調試。

雖然您可以復制 Spring Boot 的 jar 文件,但我們通常建議您使用支持依賴管理的構建工具(比如 Maven 或者 Gradle)。

您可以將 Spring Boot 應用部署到任何一個 Servlet 3.0+ 兼容容器中。

雖然您可以在 Java 6 或者 Java 7 上使用 Spring Boot,但我們還是強烈推薦您使用 Java 8+。

1.3、Spring Boot資源

官網:
https://spring.io/projects/spring-boot

https://spring.io

官方文檔:

https://docs.spring.io/spring-boot/docs/current/reference/html/

官方文檔翻譯:
https://www.springcloud.cc/spring-boot.html

http://felord.cn/_doc/_springboot/2.1.5.RELEASE/_book/

https://github.com/DocsHome/springboot

banner生成:

https://www.bootschool.net/ascii

1.4、前置學習內容

視頻bilibili:

(1)、Java編程(JavaSE、JavaWeb、反射、泛型、多線程、AJAX)

(2)、Maven快速學習教程

(3)、Spring

(4)、Spring MVC(IDEA、Maven、SSM框架集成、多模塊)

(5)、MyBatis快速學習教程

博客園文章:

(1)、Spring

(2)、Spring MVC

(3)、MyBatis

(4)、Maven

1.5、其它說明

(1)、本教程有許多內容來自互聯網,如果侵害了您的版權我將迅速處理

(2)、本教程僅針對有一定基礎的Java學習或開發者,聽課的對象是全棧開發班的學員,僅需使用Spring Boot開發可以提供給前端的后台服務即可,如果您想精通Spring Boot可能不適合您

(3)、教學全程都會錄視頻,發布在bilibili,請搜索“張果1”

(4)、該教程使用Spring Boot2

(5)、開發工具使用IDEA,Java版本是1.8

二、我的第一個SpringBoot程序

 2.1、生成項目模板

2.1.1、在線生成項目模板

為方便我們初始化項目,Spring Boot給我們提供一個項目模板生成網站。

(1). 打開瀏覽器,訪問:https://start.spring.io/

(2). 根據頁面提示,選擇構建工具,開發語言,項目信息等。

(3). 點擊 Generate the project,生成項目模板,生成之后會將壓縮包下載到本地。

當然,也可以在線預覽項目生成后的代碼,只需點擊如下按鈕即可:

 在新窗口中就可以查看生成的代碼了:

(4). 使用IDE導入項目,我這里使用IDEA,通過導入Maven項目的方式導入。

 

選擇Maven項目:

 多數情況下都直接Next就可以了,導入成功的項目如下所示:

2.1.2、IDE(集成開發工具)生成項目模板

(1)、創建新項目

 (2)、選擇Spring Initializr

  (3)、選擇填寫項目信息

 (4)、添加依賴

 (5)項目位置與名稱設定

 點擊完成就創建成功。

2.2、添加控制器

 在“com.gdnf.hello”這個包下面添加一個類取名“HelloController”:

 添加一個Action,並注解好:

package com.gdnf.hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController //注解告訴Spring將結果字符串直接呈現給調用者
public class HelloController {

    @RequestMapping("/hi")  //路徑映射
    public String hello(){
        return "Hello Spring Boot!";
    }
}

添加成功后:

2.3、啟動並運行

點擊右上角綠色箭頭就可以直接運行了,如要端口被占用(默認8080),可以配置修改,控制台信息如下:

 在瀏覽器中輸入:localhost:8081/hi就可以訪問到定義到的action,如下所示

 

2.4、Maven打包

點擊IDEA右側Maven Projects目錄,雙擊Lifecycle中的package命令就可以打包了:

打包時對網絡有一定要求,成功時提示如下:

2.5、脫離開發環境運行jar包

target上右鍵Show in Explorer,在文件夾中顯示目錄:

 創建一個可批處理文件run.bat,內容如下:

java -jar hello2-0.0.1-SNAPSHOT.jar
注意:hello2-0.0.1-SNAPSHOT.jar是包名,需要根據實際打包的名稱修改,另外要注意先停止原IDEA的程序運行,防止端口占用
點擊運行效果如下:

查看運行效果如下:


三、SpringBoot項目組成與原理分析

3.1、默認目錄結構

剛創建好的Spring Boot的項目結構比較簡單,只包含三個文件夾。

src/main/java 放置程序開發代碼

src/main/resources 放置配置文件

src/test/java 放置測試程序代碼

而在其下,包含以下主要文件。

xxxApplication.java 應用的啟動類,包含MAIN方法,是程序的入口

application.properties 一個空的配置文件,后續可以配置數據源等信息,比如修改端口號

xxxApplicationTests.java 一個簡單的單元測試類

pom.xml mave的配置文件,是管理整個項目開發流程的核心文件

3.2、注解與代碼

3.2.1、@RestController和@RequestMapping 注解

Example類的第一個注解是@RestController這被稱為 構造型注釋。它為閱讀代碼的人提供了提示,並為Spring提供了該類扮演特定角色的提示。在這種情況下,我們的類是一個web @Controller,所以Spring在處理傳入的Web請求時會考慮它。

@RequestMapping注解提供“路由”信息。它告訴Spring任何帶有/路徑的HTTP請求都應該映射到home方法。

@RestController注解告訴Spring將結果字符串直接呈現給調用者。

@RestController的作用等同於@Controller + @ResponseBody

3.2.2、@EnableAutoConfiguration注解

第二個類級別注釋是@EnableAutoConfiguration。這個注釋告訴Spring Boot根據你添加的jar依賴關系“猜測”你想要如何配置Spring。由於spring-boot-starter-web添加了Tomcat和Spring MVC,因此自動配置假定您正在開發Web應用程序並相應地設置Spring。

Starters和自動配置

自動配置旨在與“Starters”配合使用,但這兩個概念並不直接相關。您可以自由選擇並在首發之外選擇jar依賴項。Spring Boot仍然盡力自動配置您的應用程序。

3.2.3、main方法

我們的應用程序的最后一部分是main方法。這只是遵循應用程序入口點的Java約定的標准方法我們的主要方法是通過調用run來委托Spring Boot的SpringApplication類。SpringApplication引導我們的應用程序,從Spring開始,然后啟動自動配置的Tomcat Web服務器。我們需要將Example.class作為參數傳遞給run方法,以告訴SpringApplication哪個是主要的Spring組件。還會傳遞args數組以公開任何命令行參數。

3.3、SpringBoot 起步依賴原理分析

3.3.1、spring-boot-starter-parent

在spring-boot-starter-parent中定義了各種技術的版本信息,組合了一套最優搭配的技術版本。

在各種starter中,定義了完成該功能需要的坐標合集,其中大部分版本信息來自於父工程。

每個版本的SpringBoot都會對兼容的插件進行版本的控制(版本鎖定)。

  • 按住Ctrl點擊pom.xml中的spring-boot-starter
    •     <!--所有的springboot應用都要以該工程為父工程-->
          <parent>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-parent</artifactId>
              <version>2.2.7.RELEASE</version>
          </parent>
  • 再按住Ctrl點擊pom.xml中parent的spring-boot-starters 
    •   
        <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-dependencies</artifactId>
          <version>2.2.7.RELEASE</version>
          <relativePath>../../spring-boot-dependencies</relativePath>
        </parent>
  • 再按住Ctrl點擊pom.xml中parent的spring-boot-parent
    •   
      <?xml version="1.0" encoding="utf-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.2.7.RELEASE</version>
        <packaging>pom</packaging>
        。。。
        
        <properties>
          。。。
          <json-path.version>2.4.0</json-path.version>
          <jstl.version>1.2</jstl.version>
          <jtds.version>1.3.1</jtds.version>
          <junit.version>4.12</junit.version>
          <junit-jupiter.version>5.5.2</junit-jupiter.version>
          <kafka.version>2.3.1</kafka.version>
          <kotlin.version>1.3.72</kotlin.version>
          <kotlin-coroutines.version>1.3.5</kotlin-coroutines.version>
          <lettuce.version>5.2.2.RELEASE</lettuce.version>
          <liquibase.version>3.8.9</liquibase.version>
          <log4j2.version>2.12.1</log4j2.version>
          <logback.version>1.2.3</logback.version>
          <lombok.version>1.18.12</lombok.version>
          。。。
          <spring-amqp.version>2.2.6.RELEASE</spring-amqp.version>
          <spring-batch.version>4.2.2.RELEASE</spring-batch.version>
          <spring-cloud-connectors.version>2.0.7.RELEASE</spring-cloud-connectors.version>
          <spring-data-releasetrain.version>Moore-SR7</spring-data-releasetrain.version>
          <spring-framework.version>5.2.6.RELEASE</spring-framework.version>
          <spring-hateoas.version>1.0.5.RELEASE</spring-hateoas.version>
          <spring-integration.version>5.2.6.RELEASE</spring-integration.version>
          <spring-kafka.version>2.3.8.RELEASE</spring-kafka.version>
          <spring-ldap.version>2.3.3.RELEASE</spring-ldap.version>
          <spring-restdocs.version>2.0.4.RELEASE</spring-restdocs.version>
          <spring-retry.version>1.2.5.RELEASE</spring-retry.version>
          <spring-security.version>5.2.4.RELEASE</spring-security.version>
          <spring-session-bom.version>Corn-SR2</spring-session-bom.version>
          <spring-ws.version>3.0.9.RELEASE</spring-ws.version>
          <sqlite-jdbc.version>3.28.0</sqlite-jdbc.version>
          <sun-mail.version>${jakarta-mail.version}</sun-mail.version>
          <thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
          <thymeleaf-extras-data-attribute.version>2.0.1</thymeleaf-extras-data-attribute.version>
          <thymeleaf-extras-java8time.version>3.0.4.RELEASE</thymeleaf-extras-java8time.version>
          <thymeleaf-extras-springsecurity.version>3.0.4.RELEASE</thymeleaf-extras-springsecurity.version>
          <thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
          <tomcat.version>9.0.34</tomcat.version>
          。。。。
        </properties>
        
        <dependencyManagement> 版本鎖定
          <dependencies>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-test</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-test-autoconfigure</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-actuator</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-actuator-autoconfigure</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-autoconfigure</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-autoconfigure-processor</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-configuration-metadata</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-configuration-processor</artifactId>
              <version>2.2.7.RELEASE</version>
            </dependency>
            。。。
        </dependencyManagement>
        。。。
      </project>

      從上面的spring-boot-starter-dependencies的pom.xml中我們可以發現,一部分坐標的版本、依賴管理、插件管理已經定義好,所以我們的SpringBoot工程繼承spring-boot-starter-parent后已經具備版本鎖定等配置了,就不需要開發人員自己去版本控制了。所以起步依賴的作用就是進行依賴的傳遞。

3.3.2、spring-boot-starter-web

我們的工程繼承parent,引入starter后,通過依賴傳遞,就可以簡單方便獲得需要的jar包,並且不會存在
版本沖突等問題。

從上面的spring-boot-starter-web的pom.xml中我們可以發現,spring-boot-starter-web就是將web開發要使用的
spring-web、spring-webmvc等坐標進行了“打包”,這樣我們的工程只要引入spring-boot-starter-web起步依賴的
坐標就可以進行web開發了,同樣體現了依賴傳遞的作用。

四、Vue+Axios+Spring Boot用戶管理

4.1、Vue.js

Vue (讀音 /vjuː/,類似於 view) 是一套用於構建用戶界面的漸進式框架。與其它大型框架不同的是,Vue 被設計為可以自底向上逐層應用。Vue 的核心庫只關注視圖層,不僅易於上手,還便於與第三方庫或既有項目整合。另一方面,當與 現代化的工具鏈以及各種 支持類庫結合使用時,Vue 也完全能夠為復雜的單頁應用提供驅動。

如果你已經是有經驗的前端開發者,想知道 Vue 與其它庫/框架有哪些區別,請查看 對比其它框架

不適合SEO、交互頻繁的,如游戲之類交互體驗網站

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>天狗商城 - 商品管理</title>
    <link rel="stylesheet" href="../css/gomall.css" />
  </head>

  <body>
    <div id="app" class="main">
      <h2 class="title"><span>天狗商城 - 商品管理</span></h2>
      <table border="1" cellspacing="0" cellpadding="0" width="100%" class="tab">
        <tr>
          <th>序號</th>
          <th>編號</th>
          <th>名稱</th>
          <th>單價</th>
          <th>庫存</th>
          <th>小計</th>
          <th>操作</th>
        </tr>
        <!--循環渲染出產品,隔行換色,index為序號從0開始-->
        <tr v-for="(pdt,index) in products" v-bind:class="{bg:index%2==0}">
          <td>{{index+1}}</td>
          <td>{{pdt.id}}</td>
          <td>{{pdt.title}}</td>
          <td>{{pdt.price|currency}}</td>
          <td>
            <!--減少產品數量,表達式-->
            <a v-on:click="pdt.quantity<=0?0:(pdt.quantity-=1)" class="abtn"> - </a>
            <input
              v-model="pdt.quantity"
              class="quantity"
              v-on:keyup="pdt.quantity=(pdt.quantity<0?0:pdt.quantity)"
            />
            <!--增加產品數量,表達式-->
            <a v-on:click="pdt.quantity+=1" class="abtn"> + </a>
          </td>
          <!--合計,過濾器-->
          <td>{{pdt.quantity*pdt.price | currency(1)}}</td>
          <td>
            <a v-on:click="remove(index,pdt)" class="abtn">刪除</a>
            <a v-on:click="edit(index,pdt)" class="abtn">編輯</a>
          </td>
        </tr>
        <tr>
          <td colspan="7" align="right" class="total">
            {{total|currency}}
          </td>
        </tr>
      </table>

      <form id="formDetails" name="formDetails">
        <fieldset>
          <legend>商品詳細</legend>
          <p>
            <label>編號:</label>
            <input v-model="product.id" :disabled="!isAdd?'disabled':false" required="required" type="number"/>
          </p>
          <p>
            <label>名稱:</label>
            <input v-model="product.title"  required="required"/>
          </p>
          <p>
            <label>單價:</label>
            <input v-model="product.price" type="number" required="required"/>
          </p>
          <p>
            <label>庫存:</label>
            <input v-model="product.quantity" required="required"/>
          </p>
          <p>
            <label>簡介:</label>
            <textarea v-model="product.description" cols="50" rows="3" required="required"></textarea>
          </p>
          <p>
            <button @click="save" class="btn out" type="button">保存</button>
            <button @click="clear" class="btn out" type="button">清空</button>
          </p>
          <p class="poster">
            <!--圖片加載失敗時使用logo-->
            <img :src="'../img/'+product.id+'.jpg'" onerror="this.src='../img/logo.jpg'"/>
          </p>
        </fieldset>
      </form>
    </div>
    <script src="../js/vue/vue.min.js"></script>
    <script src="../js/jQuery/jquery-1.11.3.min.js"></script>
    <script type="text/javascript">
      //添加貨幣格式過濾器
      Vue.filter('currency', function (v, n) {
        if (!v) {
          return ''
        }
        return '' + parseFloat(v).toFixed(n || 2);
      })
      //實例
      var app = new Vue({
        el: '#app',
        data: {
          //商品列表
          products: [],
          //單個商品對象
          product: {},
          //是否為添加狀態
          isAdd: true,
        },
        created() {  //當實例創建完成時的鈎子
          //使用jQuery AJAX加載所有商品信息
          $.ajax({
            url: 'http://localhost:8089/api/getProductItems',
            type: 'GET',
            dataType: 'json',
            data: {},
            success: function (data) {
              //獲取后台數據,重新渲染視圖
              app.products = data;
            },
          })
        },
        computed: {  //計算屬性
          //用於計算合計的計算屬性
          total: function () {
            var sum = 0
            for (var i = 0; i < this.products.length; i++) {
              sum += this.products[i].price * this.products[i].quantity;
            }
            return sum;
          },
        },
        methods: {
          //移除商品事件
          remove(i, product) {
            if (confirm('您確定要移除嗎?')) {
              $.ajax({
                url: 'http://localhost:8089/api/RemoveProduct',
                contentType: 'application/json',
                type: 'DELETE',  //方法類型為DELETE
                dataType: 'json',
                data: JSON.stringify(product),
                success: function (data) {
                  if (data) {  //刪除成功
                    //將數據中的產品列表中對應項刪除,觸發重新渲染界面
                    app.products.splice(i, 1);
                  } else {
                    alert('移除失敗!');
                  }
                },
              })
            }
          },
          //編輯事件
          edit(index, pdt) {
            this.isAdd = false;
            //綁定當前綁定的商品對象
            this.product = pdt;
          },
          //保存事件
          save() {
            //如果是添加
            if (this.isAdd) {
              $.ajax({
                url: 'http://localhost:8089/api/AddProduct',
                contentType: 'application/json',
                type: 'POST',
                dataType: 'json',
                data: JSON.stringify(app.product),
                success: function (data) {
                  if (data) {
                    //添加成功時在前台集合中添加新商品,重新渲染視圖
                    app.products.push(app.product);
                    alert('添加成功!');
                    //清空當前項
                    app.product={};
                  } else {
                    alert('添加失敗!');
                  }
                },
              })
            } else {
              //更新
              $.ajax({
                url: 'http://localhost:8089/api/UpdateProduct',
                contentType: 'application/json',
                type: 'PUT',  //請求方法是PUT
                dataType: 'json',
                data: JSON.stringify(app.product),
                success: function (data) {
                  if (data) {
                    alert('更新成功!');
                    app.clear();
                  } else {
                    alert('更新失敗!');
                  }
                },
              })
            }
          },
          //清空
          clear(){
            //將當前操作的產品對象置空
            this.product={};
            //設置為添加狀態
            this.isAdd = true;
          }
        }
      })
    </script>
  </body>
</html>
Vue購物車示例

4.2、axios

 Vue更新到2.0之后宣告不再對vue-resource更新,推薦使用axios,axios是一個用於客戶端與服務器通信的組件,axios 是一個基於Promise 用於瀏覽器和 nodejs 的 HTTP 客戶端javaScript工具。通俗來說可以實現客戶端請求服務器端提供的服務獲得數據。

源碼與幫助:https://github.com/axios/axios

服務器端跨域支持請查看:http://www.cnblogs.com/best/p/6196202.html#_label2

點擊查看:學習資料(前端MVC Vue2學習總結(六)——axios與跨域HTTP請求、Lodash工具庫)

點擊查看:API幫助

4.3、構建項目

(1)、創建一個名為UserMIS的Spring Boot項目,依賴Spring Web

(2)、創建一個實體類User

package com.gdnf.usermis.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**用戶實體類*/
public class User implements Serializable {

    public static List<User> users=new ArrayList<>();

    static {
        users.add(new User("zhangsan",18));
        users.add(new User("lisi",19));
        users.add(new User("wangwu",91));
    }

    public User() {
    }

    public User(String username, int age) {
        this.username = username;
        this.age = age;
    }

    private String username;
    private int age;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                '}';
    }
}

(3)、創建一個用戶服務類,UserService

package com.gdnf.usermis.service;

import com.gdnf.usermis.entity.User;
import org.springframework.stereotype.Service;

import java.util.List;

/**用戶服務*/
@Service
public class UserService {

    public List<User> getAllUser(){
        return User.users;
    }

}

(4)、創建一個控制器,UserController,向前端提供服務

package com.gdnf.usermis.controller;

import com.gdnf.usermis.entity.User;
import com.gdnf.usermis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**用戶控制器*/
@RestController
public class UserController {

    @Autowired
    private UserService userService;  /**Spring將使用UserSerive實例注入給userService成員*/

    @RequestMapping("/users")
    public List<User> users(){
        return userService.getAllUser();
    }
}

(5)、測試運行后台服務

 (6)、在static文件下創建一個名為index.html的前端頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    <h2>用戶管理</h2>
    <table width="100%" border="1">
        <tr>
            <th>編號</th>
            <th>姓名</th>
            <th>年齡</th>
        </tr>
        <tr v-for="(user,index) in users">
            <td>{{index+1}}</td>
            <td>{{user.username}}</td>
            <td>{{user.age}}</td>
        </tr>
    </table>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
    var app = new Vue({
        el: "#app",
        data: {
            users: []
        },
        created() {
            axios.get('/users', {
              }).then(function (response) {
                    app.users=response.data;
                })
                .catch(function (error) {
                    console.log(error);
                })
                .then(function () {
                });
        }
    });
</script>
</body>
</html>

 (7)、運行效果

服務器端獲得客戶端的參數

    @RequestMapping("/delete")
    public int delete(@RequestParam(defaultValue ="0") int id){
        return id;
    }

五、項目實戰(見任務指導手冊)

4.1、完成小米商城后台管理系統,實現功能如下:

  • 后台登錄
  • 修改密碼
  • 用戶管理(CRUD)
  • 管理員管理(CRUD)
  • 商品類型管理(CRUD)
  • 商品管理(CRUD)
  • 訂單管理(CRUD)

4.2、完成小米商城PC端動態化,所有數據來自數據庫,消費后端向前端提供的服務

  • 商品展示
  • 登錄
  • 添加商品到購物車
  • 購買
  • 訂單管理

4.3、完成小米商城移動端動態化,所有數據來自數據庫,消費后端向前端提供的服務

  • 商品展示
  • 登錄
  • 添加商品到購物車
  • 購買
  • 訂單管理

六、作業

6.1、配置好Spring Boot開發環境。

6.2、完成第一個Spring Boot程序,要求如下:

  • 編寫后台服務接收前端提交的參數,n1,n2
  • 前端使用vue與axios消費后台提供的服務,將響應回前台的數據填寫在文檔框n3中

6.3、創建小米商城的數據庫,參考表結構如下:

1、商品類型表
編號,名稱,狀態,父節點...

2、商品表
編號,名稱,價格,詳細,海報,庫存,狀態,上貨日期...

3、用戶表
編號,用戶名,姓名,密碼,手機,郵箱,在線狀態...

4、訂單表
編號,訂單號,下單日期,訂單狀態,用戶編號,總價,地址/地址編號,留言

5、訂單商品表
編號,訂單號,商品編號,價格

6、收貨地址表
編號,用戶編號,國家,省,市,縣(區),街道/鄉鎮,地址,郵編,電話,收貨人,是否為默認地址...

6.4、拓展作業

使用Vue.js+axios+Spring Boot完成如下示例,實現CURD功能。

6.5、請按順序看完下面的視頻,調試示例

七、視頻

https://www.bilibili.com/video/BV1fi4y1S79P?share_source=copy_web

https://space.bilibili.com/87194917/video

作業解答:https://www.bilibili.com/video/BV1Hs411F71x?share_source=copy_web


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM