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檔案,把不要的東西先幹掉,最後保留如下所示即可:
-
<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>com</groupId>
- <artifactId>springboot</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- </project>
(2.2)定義父類:springboot 所有jar包版本,這裡為 2.0.5.RELEASE 版本
- <!-- Spingboot相關jar包版本 -->
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.0.5.RELEASE</version>
- </parent>
(2.3)加入springboot核心包、和web開發必須的包
- <!-- 相關jar包 -->
- <dependencies>
- <!-- Springboot核心jar包 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </dependency>
- <!-- web開發包:包含Tomcat和Springmvc -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- </dependencies>
(2.4)可以看到,我們專案測試類現在還有一個大紅叉,是因為我們剛剛吧把初始的Junit包乾掉了,現在,我們重新加入Junit包。
(2.5)加入Junit測試包,儲存。
- <!-- Junit測試jar包 -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
(2.6)重新maven update一下,小紅叉就沒有了(這裡JRE我手動換成了自己常用的jdk1.8)。
(2.7)我們建立一個App類,用來啟動專案用(建立專案的時候已經有這個類了,現在只需要修改程式碼為如下)。
- package com.springboot;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- /**
- * 專案啟動類
- */
- public class App {
- public static void main(String[] args) {
- SpringApplication.run(App.class, args);
- }
- }
裡面就一個註解,和一個啟動程式的方法。
(2.8)建立Controller:我們同樣舉例以萬年不變的User為例,取名UserController。
- package com.springboot.controller;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
- public class UserController {
- public String hello() {
- return "Hello World !!!";
- }
- }
(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檔案進行伺服器配置(注意排版保持一致,也注意鍵值對的冒號後有一個空格)
- server:
- port: 80
- session-timeout: 30
- tomcat.max-threads: 0
- tomcat.uri-encoding: UTF-8
(3.7)這樣配置後,重啟專案,我們就可以不用輸入埠號了。
【注】當你手動熟悉了上面的流程,也可以試試 如何快速建立一個 Springboot 專案。
-------------------------------------------------------------------------------------------------------------
【04】修改專案為熱部署(凡有檔案修改儲存後,自動重啟)
(4.1)開啟pom.xml,加入下面依賴,最後重啟一次專案。
- <!-- spring-boot熱部署 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-devtools</artifactId>
- </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
- <!-- thymeleaf -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
(5.2)在resoures資料夾下分別建立templates(主要放html檔案)和static(主要放css、js檔案)資料夾
(5.3)配置thymeleaf(這樣配置後,再程式碼中返回到那個頁面就不用寫過多的字首和字尾了,達到簡化效果)
- spring:
- thymeleaf:
- prefix: classpath:/templates/
- suffix: .html
- mode: HTML5
- encoding: UTF-8
- content-type: text/html
- cache: false
(5.4)再UserController.java檔案中加入如下程式碼,儲存。
- public String index(Model model) {
- model.addAttribute("name", "jack");
- model.addAttribute("age", 20);
- model.addAttribute("info", "我是一個愛學習的好青年");
- return "index";
- }
(5.5)在 templates 資料夾下加入頁面 index.html
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Index</title>
- </head>
- <body>
- 姓名:<input type="text" th:value="${name}"><br/>
- 年齡:<input type="text" th:value="${age}"><br/>
- 簡介:<input type="text" th:value="${info}"><br/>
- </body>
- </html>
(5.5)由於配置檔案進行了修改,這一次我們需要手動重啟專案,啟動後,輸入 localhost/index 訪問,可以看到資料已經成功顯示到頁面上了。
到此為止,我們前臺、後臺已經打通了,接下來就差最後一步了,把資料存入資料庫。
接下來,我們就採用 hibernate 將資料寫入到資料庫中。
首先到資料庫肯定需要jdbc連線容器和hibernate的相關jar包。
【06】配置資料庫連結
(6.1)在pom.xml中加入jdbc連結容器相關jar包。
- <!-- jdbc連結容器 -->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- </dependency>
(6.2)配置資料庫相關資訊(注意datasource的層級是在spring下):
有資料庫名稱(我這裡取名為boot)、資料庫使用者名稱、資料庫密碼等配置資訊(這裡你需要填你的資料庫帳號和密碼)
- datasource:
- url: jdbc:mysql://localhost:3306/boot
- driver-class-name: com.mysql.jdbc.Driver
- username: root
- password: zyq123
- initial-size: 10
- max-active: 20
- max-idle: 8
- min-idle: 8
(6.3)在你的mysql中建立對應的資料庫,名稱和你的配置保持一致。
(6.4)加入hibernate相關jar包(springboot中,hibernate的相關jar包已經整合到jpa中了,所以這裡只需要引入jpa一個jar依賴即可,再也不用像以前那樣引入一連串的hibernate相關包了)
- <!-- jpa(已包含hibernate) -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
(6.5)配置jpa(hibernate)相關資訊:
- jpa:
- database: mysql
- show-sql: true
- hibernate:
- ddl-auto: update
- naming:
- physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
- database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
好了,配置現在全部已經搞好了,接下來就是寫dao層了。
在寫Dao層前,先建立我們的測試實體類User
【07】建立相關實體
(7.1)我們建立一個bean資料夾來存放相關實體,首先建立一個BaseBean類,裡面主要存放每個實體的公共屬性,比如:id,建立人,建立時間,更新人,更新時間等,這裡我們就只寫一個公共屬性ID來演示。
- package com.springboot.bean;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.MappedSuperclass;
- public class BaseBean {
- /**
- * 自增長ID
- */
- private Long id;
- }
(7.2)建立User實體類
- package com.springboot.bean;
- import javax.persistence.Entity;
- import javax.persistence.Table;
- public class User extends BaseBean {
- private String name;
- private int age;
- private String info;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String getInfo() {
- return info;
- }
- public void setInfo(String info) {
- this.info = info;
- }
- }
(7.3)建立Service層介面
- package com.springboot.service;
- import com.springboot.bean.User;
- public interface UserService {
- /**
- * 儲存使用者物件
- * @param user
- */
- void save(User user);
- }
(7.4)建立Service實現類(實現先暫時不管,等我們寫了dao層再回來補上)
- package com.springboot.service.impl;
- import org.springframework.stereotype.Service;
- import com.springboot.bean.User;
- import com.springboot.service.UserService;
- public class UserServiceImpl implements UserService {
- public void save(User user) {
- // TODO Auto-generated method stub
- }
- }
(7.5)加入dao層,該層介面都是去繼承JpaRepository介面。
在一個專案中,我們往往會建立一個公共介面來處理到資料庫的請求,比如分頁等,然後每個介面去繼承它即可。
所以我們首先建立這個公共dao層介面:CommonDao
- package com.springboot.dao;
- import org.springframework.data.jpa.repository.JpaRepository;
- import org.springframework.stereotype.Repository;
- import com.springboot.bean.BaseBean;
- public interface CommonDao<T extends BaseBean> extends JpaRepository<T, Long> {
- }
(7.6)加入UserDao
- package com.springboot.dao;
- import org.springframework.stereotype.Repository;
- import com.springboot.bean.User;
- public interface UserDao extends CommonDao<User> {
- }
(7.7)現在回到UserServiceImpl類中,補全之前未完成的程式碼
OK,到此為止,所有鏈路都已經打通了,我們現在搞點資料測試一下。
【8】測試
(8.1)修改index.html如下:
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Index</title>
- </head>
- <body>
- <form action="/save" method="post">
- 姓名:<input type="text" th:value="${name}" name="name"><br/>
- 年齡:<input type="text" th:value="${age}" name="age"><br/>
- 簡介:<input type="text" th:value="${info}" name="info"><br/>
- <button>儲存</button>
- </form>
- </body>
- </html>
(8.2)再UserController類中增加儲存使用者的方法:
- private UserService userService;
- public String save(User user) {
- userService.save(user);
- return "save success !";
- }
(8.3)重啟專案,再次訪問 localhost/index
(8.4)修改頁面資料,點選儲存
(8.5)頁面提示了 save success !則說明後臺所有鏈路成功打通,資料儲存成功!
(8.6)我們進入資料庫,重新整理boot資料庫,發現已經建立了的user實體表。
(8.7)開啟user表,我們可以發現介面的資料已經成功的幫我們儲存到資料庫中了。
【9】讀取資料庫資訊到頁面展示(應讀者需求,這小節是幾個月後續寫的內容)
(9.1)開啟service層介面,新增獲取使用者物件的方法定義。
- /**
- * 獲取所有使用者物件
- * @return
- */
- List<User> getUserList();
(9.2) 在實現類中新增方法的實現
- public List<User> getUserList() {
- return userDao.findAll();
- }
(9.3) 在Controller層中新增接受請求的方法
- public String userList(Model model) {
- List<User> userList = userService.getUserList();
- model.addAttribute("userList", userList);
- return "list";
- }
看到有的新同學留言,不知道Controller方法的含義,那麼這裡我補充說下:
1處:這個註解裡寫的是你前臺頁面發的請求路徑,規範寫法來講,要與方法同名;
2處:這個物件,是用於儲存資料,將資料帶回頁面;
3處:前面那個藍色的userList是鍵,後面那個是你具體的資料,頁面需要根據你的鍵從model裡取資料。
4處:list為你返回的頁面檔案,比如我們這裡為 list.html (配置檔案中已經配了尾綴,所以這裡不寫後面的.html)
(9.4)我們新增一個展示頁面 list.html
- <html>
- <head>
- <meta charset="UTF-8">
- <title>使用者列表</title>
- </head>
- <body>
- <a href="/"><button>返回新增頁面</button></a>
- <div align="center">
- <table style="border: 1px solid;">
- <tr>
- <th>姓名</th>
- <th>年齡</th>
- <th>介紹</th>
- </tr>
- <tr th:each="user:${userList}">
- <td th:text="${user.name}"></td>
- <td th:text="${user.age}"></td>
- <td th:text="${user.info}"></td>
- </tr>
- </table>
- </div>
- </body>
- </html>
(9.5) 我們在瀏覽器上輸入 localhost/userList,則可以看到資料庫中的使用者資料了
(9.6)點選這個按鈕,可以直接跳轉到新增使用者頁面
(9.7)來到頁面後,我們可以繼續新增使用者,點選儲存。
(9.8)然後再次訪問列表頁面,可以看到新資料庫我們也能看見了。
至此為止!所有springboot資料從前臺到資料庫,以及資料庫到前臺,已經完全實現了!我相信你也會了!
要是還不會,沒關係!我這裡還有原始碼給你,記得修改配置檔案中資料庫的帳號和密碼哦!
原始碼:https://pan.baidu.com/s/1wGEhuPo52F5-w2daAtN_ag
(包含1-8節,第9節自己弄,總得自己寫點什麼才能真正學到!)
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
專案寫好了,你是不是想迫不及待的發版上去?沒問題,釋出公網的小白教程也有!
相關連結:網站開發:從寫程式碼到公網訪問整個流程
----------------------------------------------------------------------------------------------------