文章目錄
SpringBoot
1、簡介
Servlet+jsp:原生開發,十分的麻煩,在web.xml和代碼中有很多的重複代碼
Spring:從2003年Spring出現到現在,Spring已經變得不是那麼簡單了,裏面配置文件過於繁瑣。再加上集成很多的框架,會導致程序變得很臃腫
SpringBoot:簡化配置文件,可以簡單的理解爲Spring的升級版,原來Spring中的很多配置文件要手動配置,而SpringBoot可以自動配置,簡化開發,將注意力放在具體的代碼上,而不是配置文件
在SpringBoot中自動配置web.xml、Tomcat服務器、Maven依賴等,寫一個Web項目就好比寫一個Java的Hello World程序一樣簡單
2、第一個SpringBoot程序
1、打開IEDA,構建一個SpringBoot程序
2、填寫項目基本信息
3、勾選啓動器(Spring web),相當於幫你配置好了Spring和SpringMVC、Tomcat等
4、選擇文件位置,等待下載所有的Maven依賴,第一次下載會比較慢,耐心等待
5、新建Controller包,創建HelloController類
要在主啓動類的同級或子級目錄下新建包,否則項目識別不了
package org.westos.springbootdemo.controller;
@Controller
public class HelloController {
@RequestMapping("/hello")
//只返回json字符串,而不是頁面
@ResponseBody
public String hello() {
return "Hello,springBoot!";
}
}
6、啓動主啓動類,訪問測試
發現Controller返回的Hello,springBoot! 過來了
3、自定義項目啓動Log
實現自定義的SpringBoot啓動logo
在線banner生成網站:https://www.bootschool.net/ascii
在SpringBoot項目的resource目錄下新建banner.txt
,將生成的banner粘貼進去就OK了
4、pom.xml講解
1、怎麼啓動的
我們創建的SpringBoot程序中會默認配置一個項目名Application類
,這個類就是當前項目的主啓動類,用來開啓服務,下來我們看這個類的代碼
//只要標註了這個註解,就代表是一個SpringBoot應用
@SpringBootApplication
public class SpringbootdemoApplication {
public static void main(String[] args) {
//啓動方法,調用SpringApplication類的run方法
//參數爲當前類的class對象,main方法的args參數
SpringApplication.run(SpringbootdemoApplication.class, args);
}
}
下來我們刪掉項目原來的主啓動類,自己創建一個
//1、添加SpringBootApplication註解
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
//2、調用SpringApplication類的run方法
SpringApplication.run(MyApplication.class, args);
}
}
啓動項目,發現項目依然可以啓動起來,沒有問題。
那麼,SpringApplication類的run方法究竟是怎麼執行起來的呢?
我們點進源碼看一下,發現真正調用的這個run方法
2、依賴怎麼配置的
我們並沒有像spring中那樣配置Tomcat、servlet、spring、Maven依賴等,這些都是怎麼生效的呢
pom.xml研究
- 父依賴
<!--pom.xml中父依賴
spring-boot-starter就是一個啓動類
1、裏面有常用的絕大部分依賴,如果在裏面有,就不用在pom.xml文件中單獨進行配置了,沒有再進行配置
2、進行插件和資源過濾等管理
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!--我們點進org.springframework.boot
發現在spring-boot-dependencies中進行了絕大部分依賴的導入
所以在pom.xml就不用再單獨進行配置了
-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath>../../spring-boot-dependencies</relativePath>
</parent>
......
<resources>
<!--資源過濾-->
</resources>
......
<pluginManagement>
<!--插件管理-->
</pluginManagement>
......
- 啓動器
官網鏈接:https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/html/using-spring-boot.html#using-boot,在裏面有所有的場景啓動器
<dependencies>
<!--spring-boot-starter
場景啓動器,會自動導入對應場景的依賴
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
5、三種配置文件
SpringBoot中配置文件的類型:yml、yaml、properties,現在官方推薦使用yml,但是仍然是properties配置文件使用的較多
1、application.properties
在application.properties配置文件中可以編寫一些SpringBoot的配置
-
配置Tomcat服務器端口
server.port=9090
這時候我們輸入localhost:8080/就訪問不到,而輸入localhost:9090/就可以
- 還可以進行mybatis、spring等的配置,所有的配置都可以在裏面進行
2、yaml配置
我們在pom.xml中點進
發現裏面的配置文件過濾有好幾種格式
yaml語法:
空格嚴格要求,縮進嚴格要求(一個縮進是兩個空格)
行首一般是兩個空格,代表從屬關係,鍵與值之間一般是一個空格隔開
#普通鍵值對
key: value
name: zhangsan
#map/對象
key:
k1: v1
k2: v2
person:
name: zhangsan
age: 23
#list/數組
key:
- v1
- v2
pets:
- dog
- cat
#還可以向json一樣,有行內寫法,比如寫person對象
person: {name: zhangsan,age: 23}
#寫數組
pets: [dog,cat]
5、SpringBoo集成MyBatis
mybatis所有的包都要手動導入maven依賴
1、導入依賴
<!--導入mybatis和mysql依賴-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2、配置mysql連接
- 使用application.properties
#配置mysql數據庫
# mysql 5 和 mysql 8 的區別
# mysql 5 :driver-class-name=com.mysql.jdbc.Driver
# mysql 8 :driver-class-name=com.mysql.cj.jdbc.Driver,在URL中要編寫時區配置
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding-utf-8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 使用application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding-utf-8
3、測試數據源
package org.westos.springbootdemo;
@SpringBootTest
class SpringbootdemoApplicationTests {
//自動導入數據源
@Autowired
private DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//查看默認的數據源
System.out.println(dataSource.getClass());
//查看連接信息
Connection connection = dataSource.getConnection();
System.out.println(connection);
//關閉連接
connection.close();
}
}
默認的是Hikari數據源
4、創建pojo包,創建User實體類
導入lombok依賴
<!-- lombok依賴 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
package org.westos.springbootdemo.pojo;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
5、創建Mapper接口及mapper.xml
UserMapper接口
package org.westos.springbootdemo.mapper;
@Repository//代表持久層的
@Mapper
public interface UserMapper {
//獲得所有的用戶信息
List<User> getUserList();
}
UserMapepr.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="org.westos.springbootdemo.mapper.UserMapper">
<select id="getUserList" resultType="User">
select * from `user`;
</select>
</mapper>
6、配置別名及xml掃麪包
mybatis:
type-aliases-package: org.westos.springbootdemo.pojo
mapper-locations: classpath:org/westos/springbootdemo/mapper/*.xml
7、創建UserController類
package org.westos.springbootdemo.controller;
@RestController
public class MyBatisController {
@Autowired
private UserMapper mapper;
@RequestMapping("/mybatis")
public String getUserList() {
List<User> list = mapper.getUserList();
return list.toString();
}
}
8、測試運行
發現有報錯,說getUserList方法找不到,所以我們檢查UserMapper.xml文件和在application.yml中的配置,沒發現什麼問題
這個時候,我們打開target目錄,發現UserMapper.xml文件根本就沒有編譯進來
原來是pom.xml文檔中的過濾出了問題,點進parent標籤裏的artifactId值,發現過濾器中沒有設置過濾xml文件,所以在target目錄中纔沒有輸出UserMapper.xml
那麼找到了問題,只需要在pom.xml中添加xml過濾就好了
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<!--添加xml的過濾-->
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
然後運行程序,數據庫中的信息就顯示出來了
6、SpringBoot頁面傳值
當我們啓動SpringBoot時,輸入http://localhost:8080/發現顯示的是頁面不存在,沒有默認的index首頁,那麼我們怎麼定製首頁呢?
1、首頁存放的位置
首先我們先看首頁能存放的位置,在ResourceProperties類下存放着我們的一些資源路徑,可以輸入類名,點進去看一下
public class ResourceProperties {
//我們可以看到,在CLASSPATH_RESOURCE_LOCATIONS變量中定義了我們資源的存放路徑
//除了創建項目開始resources目錄下就有的static、templates包之外,還能掃描public、resources目錄
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
private String[] staticLocations;
private boolean addMappings;
private final ResourceProperties.Chain chain;
private final ResourceProperties.Cache cache;
所以resources目錄下除了已有的static、templates包之外,還能創建public、resources目錄
2、測試resources目錄下文件夾
在resources目錄下創建public、resources目錄
在templates目錄下創建index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<h1>Hello,這是我的首頁!</h1>
</body>
</html>
啓動項目,輸入localhost:8080/index.html,發現404,頁面找不到
這是因爲templates目錄下的資源只能通過Controller跳轉訪問,不能直接訪問資源,類似於web項目中的WEB-INF目錄
將index.html文件挪到public目錄下,重新運行項目
發現可以直接訪問首頁,再將index.html文件分別挪到static和resources目錄下,發現同樣可以訪問到。
templates目錄下的文件只能由Controller跳轉訪問,public、static、resources目錄下文件可以直接訪問
3、跳轉到templates目錄下文件
將index.html文件再次挪到templates目錄下,創建IndexController類
package org.westos.springbootdemo.controller;
@Controller
public class IndexController {
//只要訪問localhost:8080/,就跳轉到index.html頁面
@RequestMapping("/")
public String index() {
System.out.println("請求進來了");
//跳轉到首頁
return "index";
}
}
啓動項目,訪問localhost:8080/,發現頁面404
原來這是因爲SpringBoot在解析頁面的時候默認使用的是thymeleaf,所以要導入thymeleaf的依賴,只要在SpringBoot中編寫頁面跳轉,就要導入這個依賴
<!--導入thymeleaf依賴,如果要編寫頁面,就要使用這個依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
再次啓動項目,發現跳轉到templates目錄下的首頁了
4、頁面傳值
在後端Controller中使用Model對象傳值
在前端使用thymeleaf表達式,th:xxx
接收後端的值
編寫IndexController類
package org.westos.springbootdemo.controller;
@Controller
public class IndexController {
//只要訪問localhost:8080/,就跳轉到index.html頁面
@RequestMapping("/")
public String index(Model model) {
//使用Model對象進行傳值
//傳字段
model.addAttribute("msg","Hello!");
//傳對象
model.addAttribute("user",new User(8,"李四","123"));
//傳集合
model.addAttribute("lists", Arrays.asList("語文","數學","英語"));
//跳轉到首頁
return "index";
}
}
編寫index.html頁面
- 導入命名空間:
xmlns:th="http://www.thymeleaf.or"
- 使用
th:xxx
取值
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.or">
<head>
<meta charset="UTF-8">
<title>首頁</title>
</head>
<body>
<!--取普通字段-->
<h1 th:text="${msg}"></h1>
<!--取對象屬性-->
<h3 th:text="${user.name}"></h3>
<!--取集合遍歷-->
<a th:each="list:${lists}" th:text="${list}"></a>
<br>
<!--行內寫法,和上面的寫法效果一樣-->
<a th:each="list:${lists}">[[${list}]]</a>
</body>
</html>
基本thymeleaf表達式語法