使用SpringBoot搭建Web專案

林靜生寒發表於2021-01-14

序言

從簡入深的使用SpringBoot搭建一個Web專案,同時也包括一些小的問題。第一篇博文是以較為簡單的方式完成一個可以連線資料庫的Springboot web程式。之前自己學習的時候看網上的教程總是感覺有點太大,我只是想最簡單的搭建一個可以執行的專案,之後再去深究細節。每個教程的配置還都不一樣,讓我不知所措,所以我就寫了這篇博文來記錄自我感覺的較簡單的步驟較少的方法去搭建一個springboot web專案,不常寫文可能思路有點混亂。

Code

建立專案

這裡使用的IDE是IDEA,選擇軟體左上角File -> New -> Project來建立一個新的專案

選擇Spring Initializr來初始化我們的SpringBoot專案,選擇JDK8之後點選Next,接下來的點選Next操作就不做說明了

在如下介面我們設定包名,專案型別選擇Maven專案,語言選擇Java,打包方式選擇Jar,Java版本選擇8

依賴這部分,我們分別選擇Web下的Spring Web,Template Engines下的Thymeleaf(為以後挖坑),SQL下的MyBatis Framework,當然這裡也可以建立專案之後手動在POM檔案中寫入,不過這樣更方便一些。

接下來選擇專案的存放路徑,即可完成專案的建立,建立完成專案開啟專案之後IDEA右下角會彈出Maven projects need to be imported彈窗,選擇Enable Auto-Import即可,這樣Maven就可以自己下載依賴。

目錄結構

我們開啟新建的專案之後大致如下圖所示。.idea資料夾下存放的是IDEA專案的配置檔案,比如compiler.xml 配置了JDK版本,encodings.xml 配置了編碼型別,該資料夾我們不需要過多瞭解。.mvn資料夾下存放的是Maven的配置和相關Jar包。src資料夾是我們主要編碼的地方,src.main.java路徑下是我們編寫java程式碼的地方,src.main.resources是我們存放靜態資源,頁面以及配置檔案的地方。test資料夾是我們編寫測試程式碼的地方。.gitignore檔案配置了我們使用git時忽略上傳的檔案。HELP.md是一個幫助文件。mvnw是一個linux指令碼檔案,可以使我們執行指定版本的Maven,mvnw.cmd則是相同功能的windows版本指令碼檔案,pom.xml是Maven專案的依賴配置檔案。t1.iml是 intellij idea的工程配置檔案,裡面是當前t1 project的一些配置資訊。

我們主要關注的還是src資料夾下的檔案,其餘不重要的檔案可以隱藏,選中t1 專案,然後點選這個資料夾右下角帶三個小藍色方塊的圖示

選擇要隱藏的檔案右鍵選擇Excluded 然後這些資料夾就會變成橙黃色

點選Apply回到原來的頁面點選圖片中右上角的小齒輪,點選取消Show Excluded Files,這樣想要隱藏的檔案就消失了

測試啟動

首先我們先來測試一下SpringBoot框架是否能夠啟動,建立TestController檔案,目錄結構如下

該類的程式碼如下

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

@RestController  // 標註該類為Controller,SpringBoot會自動掃描該類
public class TestController {
    @RequestMapping("/test")  // 處理請求路徑為/test的請求
    public String test(){
        return "測試成功";  
    }
}

注:自己敲程式碼的時候會自動導包,如果是複製上去的話可能不會自動導,需要手動處理。

接下來點選下圖左側主啟動類的小箭頭或者右上角的箭頭都可以啟動專案

然後觀察控制檯的輸出,很自然的沒有執行成功,出錯了,我們看一下錯誤提示


APPLICATION FAILED TO START


Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

大體意思就是沒有配置資料庫驅動,我們也沒用到資料庫啊?為啥要配置資料庫驅動呢?還記得我們之前選擇依賴的時候選擇了mybatis嗎,原因就出在這裡,找到pom.xml檔案註釋掉mybatis依賴,重啟專案。

<!--        <dependency>-->
<!--            <groupId>org.mybatis.spring.boot</groupId>-->
<!--            <artifactId>mybatis-spring-boot-starter</artifactId>-->
<!--            <version>2.1.3</version>-->
<!--        </dependency>-->

專案成功啟動控制檯輸出如下

我們可以看到程式啟動在8080埠,在瀏覽器中輸入請求地址即可看到我們想要得到的測試成功字串

我們百度可以瞭解到mybatis是一個Java持久層框架,JDBC才是連線資料庫用到的驅動,那為什麼我們引入mybatis需要配置資料庫驅動呢?

我們從上面這張圖片可以看到mybatis-spring-boot-starter依賴包含了jdbc依賴,所以引入了mybatis就相當於引入了jdbc,再加上SpringBoot的自動配置是根據是否引入類來進行自動配置的,自然的,引入了jdbc依賴就需要配置資料庫驅動程式(選擇資料庫驅動自然是沒法自動配置的),從如下的報錯也可以得出同樣結論。

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class

連線資料庫

我們使用mysql資料庫,首先建立一個資料庫,我起的名字叫t1並建立了一張表Bear

表內欄位如下

然後隨便新增點資料,這樣我們資料庫就準備好了。

再次回到程式碼這邊,首先我們是要配置資料庫的連線資訊,在application.properties裡做如下配置

# 資料庫設定
## 資料庫驅動
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# 資料庫連線地址
spring.datasource.url=jdbc:mysql://localhost:3306/t1
# 資料庫使用者名稱
spring.datasource.username=root
# 資料庫密碼
spring.datasource.password=root

其次是匯入JDBC驅動,在pom.xml中新增如下程式碼

  <!-- mysql jdbc 驅動 https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
  <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
  </dependency>

因為我安裝的是5.7版本的mysql所以這裡我選擇的是5版本的jdbc,如果是8版本的mysql可能就需要選擇8版本的驅動了,驅動程式可以在maven倉庫找到,同時我們要解開之前對mybatis依賴的註釋。

接下來我們要建立一個實體Bear,用來承接Bear表查詢出來的資料,在t1目錄下建立controller的同級目錄entity,再在entity內建立java檔案Bear.java,內容如下

package com.ljsh.t1.entity;

public class Bear {

    private String name;
    private String type;
    private String weight;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getWeight() {
        return weight;
    }

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public Bear(String name, String type, String weight) {
        this.name = name;
        this.type = type;
        this.weight = weight;
    }
}

一個典型的pojo,下面的getter和setter方法可以在idea編碼頁面右鍵選擇 Generate -> Getter and Setter 自動生成。

再之後是對mybaitis的配置與操作,建立controller目錄同級目錄mapper,在mapper目錄中建立介面檔案TestMapper.java,程式碼內容如下

package com.ljsh.t1.mapper;

import com.ljsh.t1.entity.Bear;
import java.util.List;

public interface TestMapper {
    List<Bear> getAllBears();  //查詢Bear表所有資料,作為List查出來
}

同樣的在resources目錄下也建立一個mapper資料夾,mapper資料夾裡建立TestMapper.xml檔案,內容如下

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ljsh.t1.mapper.TestMapper">

    <select id="getAllBears"  resultType="com.ljsh.t1.entity.Bear">
        select
        *
        from Bear
    </select>
</mapper>

在T1Applicatin檔案也就是主啟動類中新增一個註解如下

package com.ljsh.t1;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.ljsh.t1.mapper") //掃描mapper介面類
public class T1Application {

    public static void main(String[] args) {
        SpringApplication.run(T1Application.class, args);
    }

}

最後在application.properties中增加一行

# 指向對映xml檔案目錄
mybatis.mapperLocations=classpath:mapper/*.xml

現在的目錄結構如下

通過在主啟動類上配置@MapperScan註解,讓springboot掃描需要實現的Mapper介面檔案。通過配置檔案裡xml地址的配置,讓Mapper介面和Mapper的xml實現可以對應起來。

最後我們在TestController裡修改程式碼

package com.ljsh.t1.controller;

import com.ljsh.t1.entity.Bear;
import com.ljsh.t1.mapper.TestMapper;
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  // 標註該類為Controller,SpringBoot會自動掃描該類
public class TestController {

    @Autowired
    TestMapper testMapper;  //自動注入

    @RequestMapping("/test")  // 處理請求路徑為/test的請求
    public Object test(){
        List<Bear> bears = testMapper.getAllBears();
        return bears;
    }
}

重新啟動專案訪問http://localhost:8080/test我們會收到從資料庫查詢出來的資料

這時候檢視控制檯可能會發現一些警告

Thu Jan 14 22:45:15 CST 2021 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

修改application.properties中的資料庫連線為如下即可消除警告

spring.datasource.url=jdbc:mysql://localhost:3306/t1?useSSL=false

結束語

本來的出發點是以最簡單的方式搭建一個能跑起來的web專案,但是寫完了感覺還是有點複雜,但有基礎的話還是很好理解的。之後應該還會根據這個demo更新 mvc / 配置 /mybatis 具體的一些細節,也是自己的一次複習,如果有時間的話。

相關文章