1. 程式人生 > 其它 >java開發之Springboot專案搭建(前端到資料庫,超詳細)

java開發之Springboot專案搭建(前端到資料庫,超詳細)

java開發之Springboot專案搭建(前端到資料庫,超詳細)

java開發之Springboot專案搭建(前端到資料庫,超詳細)

下面詳細談談我的第一個springboot專案搭建,希望會給還在摸索的同學一點幫助。

專案說明:

開發環境:Eclipse 4.42

框架:Springboot

工具:Maven

前端:Html、Thymeleaf

後臺:Java、JPA (Hibernate)

資料庫:Mysql

為什麼要搭建Springboot專案?

教科書式的闡述這裡就不說了,我就總結為兩個詞語 “簡單、方便”。

為了更加清晰的展示,現在我用一個全新的工作空間來演示springboot專案的搭建過程。

【01】建立一個簡單的maven專案(如果Eclipse不支援Maven專案建立,請先自行安裝Maven,不會問度娘):

(1.1)右鍵單擊 --> New --> Other

(1.2)輸入Maven,選中Maven Project,點選Next。

(1.3)勾選 Use default Workspace location,點選Next。

(1.4) 選擇 maven-archetype-quickstart,點選Next。

(1.5)填寫GroupId、ArtifactId、為了統一,你們也照著這個來寫吧,真實就是填公司性質(.com)和域名(springboot)。填寫好後,Package一欄會自動生成,這也就是專案中的包名,點選Finish。

(1.6)可以看到,我們的工程已經建立成功了。但貌似現在有一些不完美的地方需要解決。

(1.7)工程建立成功後,可以看到又一個小紅叉,雖然不影響程式執行,但面對有強迫的我們,看著很少難受。選中工程:右鍵單擊-->Maven --> Update Project

(1.8)什麼都不管,直接點選OK

(1.9)奈斯!小紅叉已經被我們消滅了!

【02】加入Springboot框架

(2.1)我們先雙擊開啟pom.xml檔案,把不要的東西先幹掉,最後保留如下所示即可:

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com</groupId>
  5. <artifactId>springboot</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>jar</packaging>
  8. </project>

(2.2)定義父類:springboot 所有jar包版本,這裡為 2.0.5.RELEASE 版本

  1. <!-- Spingboot相關jar包版本 -->
  2. <parent>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-parent</artifactId>
  5. <version>2.0.5.RELEASE</version>
  6. </parent>

(2.3)加入springboot核心包、和web開發必須的包

  1. <!-- 相關jar包 -->
  2. <dependencies>
  3. <!-- Springboot核心jar包 -->
  4. <dependency>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter</artifactId>
  7. </dependency>
  8. <!-- web開發包:包含Tomcat和Springmvc -->
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-web</artifactId>
  12. </dependency>
  13. </dependencies>

(2.4)可以看到,我們專案測試類現在還有一個大紅叉,是因為我們剛剛吧把初始的Junit包乾掉了,現在,我們重新加入Junit包。

(2.5)加入Junit測試包,儲存。

  1. <!-- Junit測試jar包 -->
  2. <dependency>
  3. <groupId>junit</groupId>
  4. <artifactId>junit</artifactId>
  5. <scope>test</scope>
  6. </dependency>

(2.6)重新maven update一下,小紅叉就沒有了(這裡JRE我手動換成了自己常用的jdk1.8)。

(2.7)我們建立一個App類,用來啟動專案用(建立專案的時候已經有這個類了,現在只需要修改程式碼為如下)。

  1. package com.springboot;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. /**
  5. * 專案啟動類
  6. */
  7. @SpringBootApplication
  8. public class App {
  9. public static void main(String[] args) {
  10. SpringApplication.run(App.class, args);
  11. }
  12. }

裡面就一個註解,和一個啟動程式的方法。

(2.8)建立Controller:我們同樣舉例以萬年不變的User為例,取名UserController。

  1. package com.springboot.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.ResponseBody;
  5. @Controller
  6. public class UserController {
  7. @RequestMapping("/hello")
  8. @ResponseBody
  9. public String hello() {
  10. return "Hello World !!!";
  11. }
  12. }

(2.9)啟動專案,執行app類中的main函式,如果正常,控制檯出現下面輸出,則專案已經啟動成功了。

(2.10)我們在位址列目輸入 localhost:8080/hello 進行訪問,如果能看到Hello world字樣,則說明專案springboot已經搭建成功了。

【03】常用配置設定
springboot專案預設配置檔案是resources資料夾下的application.yml檔案,現在專案沒有這些東西,需要手動進行建立。

(3.1)建立resources資料夾(該資料夾主要存放各種配置資源),如果專案已經有 src/main/resources資料夾,則該步驟略過。如果沒有,請按照連結所示建立資料夾:https://www.cnblogs.com/zhangyuanqiang/p/9183908.html(敝人部落格園文章)

(3.2)建立 application.yml 檔案,選中src/main/java/resources/資料夾-->New-->Other

(3.3)選擇General資料夾下的File,點選Next

(3.4)輸入application.yml,點選Finish。

(3.5) 完成建立如圖所示

(3.6)開啟application.yml檔案進行伺服器配置(注意排版保持一致,也注意鍵值對的冒號後有一個空格)

  1. server:
  2. port: 80
  3. session-timeout: 30
  4. tomcat.max-threads: 0
  5. tomcat.uri-encoding: UTF-8

(3.7)這樣配置後,重啟專案,我們就可以不用輸入埠號了。

【注】當你手動熟悉了上面的流程,也可以試試 如何快速建立一個 Springboot 專案

-------------------------------------------------------------------------------------------------------------

【04】修改專案為熱部署(凡有檔案修改儲存後,自動重啟)

(4.1)開啟pom.xml,加入下面依賴,最後重啟一次專案。

  1. <!-- spring-boot熱部署 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-devtools</artifactId>
  5. </dependency>

(4.2)然後修改返回頁面的語句,儲存,你會發現專案可以自動重啟了。

(4.3)並且也能訪問成功,說明我們的熱部署也已經配置成功了。

【05】配置 Thymeleaf

現在後臺已經OK,後臺的資料需要顯示到前端,我們這裡前端顯示,用springboot常配套的 thymeleaf(相當於c標籤),

這個使用起來很簡單,基本一用就會,會c標籤的更是一點即通。

下面是我對thymeleaf常用使用方式總結,不懂的可以看看:https://blog.csdn.net/sunnyzyq/article/details/86685697

(5.1)在pom.xml中加入thymeleaf

  1. <!-- thymeleaf -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  5. </dependency>

(5.2)在resoures資料夾下分別建立templates(主要放html檔案)和static(主要放css、js檔案)資料夾

(5.3)配置thymeleaf(這樣配置後,再程式碼中返回到那個頁面就不用寫過多的字首和字尾了,達到簡化效果)

  1. spring:
  2. thymeleaf:
  3. prefix: classpath:/templates/
  4. suffix: .html
  5. mode: HTML5
  6. encoding: UTF-8
  7. content-type: text/html
  8. cache: false

(5.4)再UserController.java檔案中加入如下程式碼,儲存。

  1. @RequestMapping("/index")
  2. public String index(Model model) {
  3. model.addAttribute("name", "jack");
  4. model.addAttribute("age", 20);
  5. model.addAttribute("info", "我是一個愛學習的好青年");
  6. return "index";
  7. }

(5.5)在 templates 資料夾下加入頁面 index.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Index</title>
  6. </head>
  7. <body>
  8. 姓名:<input type="text" th:value="${name}"><br/>
  9. 年齡:<input type="text" th:value="${age}"><br/>
  10. 簡介:<input type="text" th:value="${info}"><br/>
  11. </body>
  12. </html>

(5.5)由於配置檔案進行了修改,這一次我們需要手動重啟專案,啟動後,輸入 localhost/index 訪問,可以看到資料已經成功顯示到頁面上了。

到此為止,我們前臺、後臺已經打通了,接下來就差最後一步了,把資料存入資料庫。

接下來,我們就採用 hibernate 將資料寫入到資料庫中。

首先到資料庫肯定需要jdbc連線容器和hibernate的相關jar包。

【06】配置資料庫連結

(6.1)在pom.xml中加入jdbc連結容器相關jar包。

  1. <!-- jdbc連結容器 -->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. </dependency>

(6.2)配置資料庫相關資訊(注意datasource的層級是在spring下):

有資料庫名稱(我這裡取名為boot)、資料庫使用者名稱、資料庫密碼等配置資訊(這裡你需要填你的資料庫帳號和密碼)

  1. datasource:
  2. url: jdbc:mysql://localhost:3306/boot
  3. driver-class-name: com.mysql.jdbc.Driver
  4. username: root
  5. password: zyq123
  6. initial-size: 10
  7. max-active: 20
  8. max-idle: 8
  9. min-idle: 8

(6.3)在你的mysql中建立對應的資料庫,名稱和你的配置保持一致。

(6.4)加入hibernate相關jar包(springboot中,hibernate的相關jar包已經整合到jpa中了,所以這裡只需要引入jpa一個jar依賴即可,再也不用像以前那樣引入一連串的hibernate相關包了)

  1. <!-- jpa(已包含hibernate) -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-jpa</artifactId>
  5. </dependency>

(6.5)配置jpa(hibernate)相關資訊:

  1. jpa:
  2. database: mysql
  3. show-sql: true
  4. hibernate:
  5. ddl-auto: update
  6. naming:
  7. physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
  8. database-platform: org.hibernate.dialect.MySQL5InnoDBDialect

好了,配置現在全部已經搞好了,接下來就是寫dao層了。

在寫Dao層前,先建立我們的測試實體類User

【07】建立相關實體

(7.1)我們建立一個bean資料夾來存放相關實體,首先建立一個BaseBean類,裡面主要存放每個實體的公共屬性,比如:id,建立人,建立時間,更新人,更新時間等,這裡我們就只寫一個公共屬性ID來演示。

  1. package com.springboot.bean;
  2. import javax.persistence.GeneratedValue;
  3. import javax.persistence.GenerationType;
  4. import javax.persistence.Id;
  5. import javax.persistence.MappedSuperclass;
  6. @MappedSuperclass
  7. public class BaseBean {
  8. /**
  9. * 自增長ID
  10. */
  11. @Id
  12. @GeneratedValue(strategy = GenerationType.IDENTITY)
  13. private Long id;
  14. }

(7.2)建立User實體類

  1. package com.springboot.bean;
  2. import javax.persistence.Entity;
  3. import javax.persistence.Table;
  4. @Entity
  5. @Table(name = "user")
  6. public class User extends BaseBean {
  7. private String name;
  8. private int age;
  9. private String info;
  10. public String getName() {
  11. return name;
  12. }
  13. public void setName(String name) {
  14. this.name = name;
  15. }
  16. public int getAge() {
  17. return age;
  18. }
  19. public void setAge(int age) {
  20. this.age = age;
  21. }
  22. public String getInfo() {
  23. return info;
  24. }
  25. public void setInfo(String info) {
  26. this.info = info;
  27. }
  28. }

(7.3)建立Service層介面

  1. package com.springboot.service;
  2. import com.springboot.bean.User;
  3. public interface UserService {
  4. /**
  5. * 儲存使用者物件
  6. * @param user
  7. */
  8. void save(User user);
  9. }

(7.4)建立Service實現類(實現先暫時不管,等我們寫了dao層再回來補上)

  1. package com.springboot.service.impl;
  2. import org.springframework.stereotype.Service;
  3. import com.springboot.bean.User;
  4. import com.springboot.service.UserService;
  5. @Service
  6. public class UserServiceImpl implements UserService {
  7. @Override
  8. public void save(User user) {
  9. // TODO Auto-generated method stub
  10. }
  11. }

(7.5)加入dao層,該層介面都是去繼承JpaRepository介面。

在一個專案中,我們往往會建立一個公共介面來處理到資料庫的請求,比如分頁等,然後每個介面去繼承它即可。

所以我們首先建立這個公共dao層介面:CommonDao

  1. package com.springboot.dao;
  2. import org.springframework.data.jpa.repository.JpaRepository;
  3. import org.springframework.stereotype.Repository;
  4. import com.springboot.bean.BaseBean;
  5. @Repository
  6. public interface CommonDao<T extends BaseBean> extends JpaRepository<T, Long> {
  7. }

(7.6)加入UserDao

  1. package com.springboot.dao;
  2. import org.springframework.stereotype.Repository;
  3. import com.springboot.bean.User;
  4. @Repository
  5. public interface UserDao extends CommonDao<User> {
  6. }

(7.7)現在回到UserServiceImpl類中,補全之前未完成的程式碼

OK,到此為止,所有鏈路都已經打通了,我們現在搞點資料測試一下。

【8】測試

(8.1)修改index.html如下:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Index</title>
  6. </head>
  7. <body>
  8. <form action="/save" method="post">
  9. 姓名:<input type="text" th:value="${name}" name="name"><br/>
  10. 年齡:<input type="text" th:value="${age}" name="age"><br/>
  11. 簡介:<input type="text" th:value="${info}" name="info"><br/>
  12. <button>儲存</button>
  13. </form>
  14. </body>
  15. </html>

(8.2)再UserController類中增加儲存使用者的方法:

  1. @Autowired
  2. private UserService userService;
  1. @RequestMapping("/save")
  2. @ResponseBody
  3. public String save(User user) {
  4. userService.save(user);
  5. return "save success !";
  6. }

(8.3)重啟專案,再次訪問 localhost/index

(8.4)修改頁面資料,點選儲存

(8.5)頁面提示了 save success !則說明後臺所有鏈路成功打通,資料儲存成功!

(8.6)我們進入資料庫,重新整理boot資料庫,發現已經建立了的user實體表。

(8.7)開啟user表,我們可以發現介面的資料已經成功的幫我們儲存到資料庫中了。

【9】讀取資料庫資訊到頁面展示(應讀者需求,這小節是幾個月後續寫的內容)

(9.1)開啟service層介面,新增獲取使用者物件的方法定義。

  1. /**
  2. * 獲取所有使用者物件
  3. * @return
  4. */
  5. List<User> getUserList();

(9.2) 在實現類中新增方法的實現

  1. @Override
  2. public List<User> getUserList() {
  3. return userDao.findAll();
  4. }

(9.3) 在Controller層中新增接受請求的方法

  1. @RequestMapping("/userList")
  2. public String userList(Model model) {
  3. List<User> userList = userService.getUserList();
  4. model.addAttribute("userList", userList);
  5. return "list";
  6. }

看到有的新同學留言,不知道Controller方法的含義,那麼這裡我補充說下:

1處:這個註解裡寫的是你前臺頁面發的請求路徑,規範寫法來講,要與方法同名;

2處:這個物件,是用於儲存資料,將資料帶回頁面;

3處:前面那個藍色的userList是鍵,後面那個是你具體的資料,頁面需要根據你的鍵從model裡取資料。

4處:list為你返回的頁面檔案,比如我們這裡為 list.html (配置檔案中已經配了尾綴,所以這裡不寫後面的.html)

(9.4)我們新增一個展示頁面 list.html

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>使用者列表</title>
  6. </head>
  7. <body>
  8. <a href="/"><button>返回新增頁面</button></a>
  9. <div align="center">
  10. <table style="border: 1px solid;">
  11. <tr>
  12. <th>姓名</th>
  13. <th>年齡</th>
  14. <th>介紹</th>
  15. </tr>
  16. <tr th:each="user:${userList}">
  17. <td th:text="${user.name}"></td>
  18. <td th:text="${user.age}"></td>
  19. <td th:text="${user.info}"></td>
  20. </tr>
  21. </table>
  22. </div>
  23. </body>
  24. </html>

(9.5) 我們在瀏覽器上輸入 localhost/userList,則可以看到資料庫中的使用者資料了

(9.6)點選這個按鈕,可以直接跳轉到新增使用者頁面

(9.7)來到頁面後,我們可以繼續新增使用者,點選儲存。

(9.8)然後再次訪問列表頁面,可以看到新資料庫我們也能看見了。

至此為止!所有springboot資料從前臺到資料庫,以及資料庫到前臺,已經完全實現了!我相信你也會了!

要是還不會,沒關係!我這裡還有原始碼給你,記得修改配置檔案中資料庫的帳號和密碼哦!

原始碼:https://pan.baidu.com/s/1wGEhuPo52F5-w2daAtN_ag

(包含1-8節,第9節自己弄,總得自己寫點什麼才能真正學到!)

----------------------------------------------------------------------------------------------------

其他相關推薦:

(1)Springboot基於註解實現自動任務

(2)Springboot之JPA常用查詢方法

(3)Springboot 攔截器

----------------------------------------------------------------------------------------------------

專案寫好了,你是不是想迫不及待的發版上去?沒問題,釋出公網的小白教程也有!

相關連結:網站開發:從寫程式碼到公網訪問整個流程

----------------------------------------------------------------------------------------------------