springBoot入門到精通-Simple

http://www.javashuo.com/article/p-exyvjkis-ea.html

1.springBoot前期準備

  • 1.環境配置:jdk,maven
  • 2.編寫工具:sts(Spring Tool Suite)
  • 3.在sts裏面配置maven
    以上百度自行解決

2.使用springBoot APi自動建立第一個maven項目

  • 1.進入這個網址:https://start.spring.io/
  • 2.進行以下配置:點擊查看
  • 3.下載好剛剛建立的Maven項目止以後進行導入:
    右單擊->import->maven->exsiting Maven projects->選中項目文件夾 點擊導入便可

判斷是否導入成功的標誌是:

打開java目錄下的.java文件,運行,控制檯出現如下內容即視爲導入成功 點擊查看運行結果

下面講一下建立的項目每個文件夾所存放以及用於存放的內容

springBoot運行程序時若是發現端口號被佔用的問題,請參考文檔

若是在瀏覽器上運行時出現:

Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Jun 30 17:24:02 CST 2015 There was an unexpected error (type=Not Found, status=404). No message available
  • 1

那麼就是由於你所建立的包不在springboot的主配置類所在包內,點擊查看詳情css

  • 什麼叫作springboot的主配置類

    含有註解@SpringBootApplication的類,好比默認建立好的主配置類是這樣子的:html

package com.test.HelloWord;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HelloWordApplication {
	public static void main(String[] args) {
		SpringApplication.run(HelloWordApplication.class, args);
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

要想使用註解,建立的包必須所有在package com.test.HelloWord內部java

舉一個例子

  • 有效的包名:package com.test.HelloWord.controller;
  • 無效的包名:package com.test.controller;

下面講一下常見的一些註解:

  • @SpringBootApplication:springboot的主配置類,該註解包含:

1.@SpringBootConfiguration ------- 2. @EnableAutoConfigurationjquery

1.@SpringBootConfigurationweb

這個註解又包含:spring

@Configuration,它表示配置類:bootstrap

  • 該類是一個配置類
  • 加了這個註解會自動放入spring 容器
  1. @EnableAutoConfiguration:使用springBoot能夠自動配置,擺脫了ssm中使用spring.xml,mybatis.xml,以及springmvc.xml文件配置的繁瑣,工做原理就是就是找到主配置類所在的包,並將該包以及所在的子包歸入控制器

spring 在啓動時會根據D:\MAVENRes\org\springframework\boot\spring-boot-autoconfigure\2.1.0.RELEASE\spring-boot-autoconfigure-2.1.0.RELEASE.jar下面的/META-INF/spring.factories自動加載第三方jar包數組

@Conditional註解:瀏覽器

  • @ConditionalOnBean(僅僅在當前上下文中存在某個對象時,纔會實例化一個Bean)
  • @ConditionalOnClass(某個class位於類路徑上,纔會實例化一個Bean)
  • @ConditionalOnExpression(當表達式爲true的時候,纔會實例化一個Bean)
  • @ConditionalOnMissingBean(僅僅在當前上下文中不存在某個對象時,纔會實例化一個Bean)
  • @ConditionalOnMissingClass(某個class類路徑上不存在的時候,纔會實例化一個Bean)
  • @ConditionalOnNotWebApplication(不是web應用)
  • 更多註解請參考 @Controller擴展註解

如何知道系統中開啓了那些自動裝配,或者禁止了哪些自動裝配

在application.properties加入debug=true便可tomcat

  • Positive matches:中包含了全部開啓的配置
  • Negative matches:中包含了全部未開啓的配置

3.配置文件以及ymls使用

1.配置文件的做用:就是對默認的配置進行修改

2.默認的全局配置文件:

  • 1.application.properties 如何使用:key=value的形式
  • 2.application.yml key:空格value(注意yml不是文本標記語言,什麼是文本標記語言:xml文件就是文本標記語言,由於xml文件符合下面這種格式:)
<server>
    <port>8888</port>
    </server>
  • 1
  • 2
  • 3

而yml如何實現更改端口,參考下面代碼:

server:
       port: 8888   注意‘:’與8888之間存在空格
  • 1
  • 2

要注意port要與server垂直對齊

3.具體如何修改默認配置舉一個小例子:

默認端口是8080,若是我想修改爲其餘的端口號只須要這步操做便可:
server.port=8081,只須要這一句話便可以把端口號改成8081
  • 1
  • 2

4.在yml文件中對象屬性進行操做:

直接看代碼:

package com.test.HelloWord.po;
@Component//做用是將此bean放入spring容器
@ConfigurationProperties(prefix="StudentPo")//做用是將StudentPo可以被yml文件識別,並能對其進行屬性的注入
public class StudentPo {
	private String name;
	private int age;
	private boolean sex;
	private Data birthday;
	private Map<String, Object> location;
	private String hobbbies[];
	private List<String> skills;
	private PetPo pet;
	此處省略構造函數以及get set方法
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

而yml文件中的內容以下:

StudentPo:
 name: zx
 age: 21
 sex: true 
 birthday: 2018/11/21
 location: {province: 江蘇省,city: 南京市,zone: 玄武區}//注:這種是對map函數的賦值方法,此處雖然沒有加引號,可是若是字段裏面有轉意符,好比\n,\t等,要想使轉意生效,就必須加雙引號
 hobbbies: 
  - 唱歌
  - 運動         //這種是對數組進行賦值的方法
 skills:
  - 計算機
  - 軟件開發    //這種是對數組進行賦值的方法
 pet:
  nickName: luckliy
  strain: 哈士奇      //這種是對屬性爲對象的賦值方法
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

測試語句以下:

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloWordApplicationTests {
	@Autowired
	StudentPo stu;//因爲已經將student加上註解:@Component//做用是將此bean放入spring容器,因此能夠進行自動注入
	@Test
	public void contextLoads() {
		System.out.println(stu.toString());
	}

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4.yml經過@ConfigurationProperties 和@Value方式注入值

  • @ConfigurationProperties:是爲了可以讓配置文件識別這個對象
  • @Value:是給單個屬性賦值
    @Value用法:
public class StudentPo {
	@Value("zx")//加上這條註解以後name的值就變爲zx
	private String name;
	@Value("23")//age就變爲23
	private int age;
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
# @ConfigurationProperties @Value
注值 批量注入 單個
spEL 不支持 支持
JSR303 支持 不支持
注入複雜類型 支持 不支持

複雜類型:除了(8個基本類型,String,Date類型之外的都是複雜類型)

下面重點講解一下JSR303校驗的用法:

@Component//做用是將此bean放入spring容器
@ConfigurationProperties(prefix="student")//做用是將StudentPo可以被yml文件識別,並能對其進行屬性的注入
@Validated//開啓jsr303數據校驗
public class StudentPo {
	@Email
	private String emial
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

經過註解@PropertySource來加載不是默認配置文件的文件,注:默認配置文件只有兩種:

  • application.properties
  • application.yml
  • 除此以外都不是默認配置文件
    具體如何使用@PropertySource,參考下面代碼

先看看conf.properties

student.age=66
  • 1

再接着看如何使用:

@Component//做用是將此bean放入spring容器
@ConfigurationProperties(prefix="student")//做用是將StudentPo可以被yml文件識別,並能對其進行屬性的注入
@Validated//開啓jsr303數據校驗
@PropertySource(value= {"classpath:conf.properties"})//做用是引入配置文件
public class StudentPo {
	private int age
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

可是這個註解有個缺陷就是僅支持.properties文件

5.@ImportResource,配置類 ,佔位符表達式

1.@ImportResource的使用:

  • 用於引入xml配置文件,因爲springBoot已經幫咱們配置好了相似於spring.xml類型的配置文件,因此當咱們直接獲取spring容器時就會出現錯誤,可是若是咱們就是想使用本身的配置文件,此時只有在主程序中加入@ImportResource註解,詳情以下:
@SpringBootApplication
@ImportResource({"classpath:spring.xml"})//此處是新加入的
public class HelloWordApplication {
	public static void main(String[] args) {
		SpringApplication.run(HelloWordApplication.class, args);
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

具體如何調用這個xml文件,咱們先看看這個xml文件的內容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/aop 
   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
   http://www.springframework.org/schema/context      
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<bean id="PetPo" class="com.test.HelloWord.po.PetPo">
	<property name="nickName" value="zhuxu"></property>
	<property name="strain" value="哈士奇"></property>
	</bean>
</beans>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

對應的PetPo對象:

package com.test.HelloWord.po;

public class PetPo {
	private String nickName;
	private String strain;
	對應的get set方法已經省略,可是必定要加進去,不然屬性就沒法注入
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

對應的測試程序:

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloWordApplicationTests {
	@Autowired
	ApplicationContext ac;//此處是爲了獲取spring容器
	@Test
	public void test1() {
		PetPo petPo= (PetPo)ac.getBean("PetPo");
		System.out.println(petPo.toString());
	}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

可是並不推薦這種方式進行屬性的注入,太麻煩,推薦使用配置類

2.配置類

配置類就是配置文件(.xml文件)配上註解的形式,如何建立配置類:

  • 在原來普通的類的基礎上加上註解:@Configuration
  • 可是通常配置類要和@Bean同時使用,@Bean就是爲了可以像spring.xml中標籤同樣,可以建立多個
    具體怎麼使用參考下面代碼:
@Configuration//加上他以後這個類就是配置類
public class AppConfig {
	@Bean//加上它以後就至關於建立了一個<bean></bean>標籤
	public PetPo ppp() {/*ppp至關於<bean id="" class=""></bean>中的id*/
		PetPo p=new PetPo();
		return p;
	/*返回的結果類型就至關於<bean id="" class=""></bean>中的class*/
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

下面寫一個測試方法本身感覺一下

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloWordApplicationTests {
	@Autowired
	ApplicationContext ac;//此處是爲了獲取spring容器
	@Test
	public void test1() {
		PetPo petPo= (PetPo)ac.getBean("p");
		System.out.println(petPo.toString());
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

3.佔位符表達式

student.age=${}
  • 1

6.springBoot多環境設置及切換

  • 默認狀況下boot會讀取application.propertiesh環境下的端口
  • 多個環境:application-環境名.properties,好比:
application-dev.properties
application-test.properties
  • 1
  • 2

至於具體怎麼切換:就是在主配置文件(application.properties)中加入:

spring.profiles.active=dev
  • 1

表示切換到dev下的端口環境

經過yml文件切換環境:

server:
  port: 1234
---
server:
  port: 8880
spring:
  profiles: dev//用於聲明環境名爲dev
---
server:
  port: 8881
spring:
  profiles: test  //用於聲明環境名test
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

這樣的話就建立好了三個環境,可是至於使用哪個環境,就得使用這樣的配置:

在主端口中這樣聲明:
server:
  port: 1234
spring:
  profiles:
    active: dev    //切換到端口到dev環境
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

如何動態切換環境:

  • 1.使用命令行:
右單擊 ->Run As->RunConfigurations->Arguments->在裏面輸入--spring.profiles.active=環境名
好比:--spring.profiles.active=dev
  • 1
  • 2
  • 2.打成jar在cmd裏面執行,下面先講解一下如何打成jar包
右單擊項目->Run As->maven build,進入以後在package便可
  • 1

下面再接着敘述如何在cmd中運行打成的jar包

  • 進入cmd
  • 先進入這個jar包所在的目錄 而後輸入指令
java -jar HelloWord-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
  • 1
  • 3.經過jvm參數指定
右單擊 ->Run As->RunConfigurations->Java Application->HellowdApplication(此處爲項目名,項目不一樣名字也不同)->右邊的Argument,
輸入 -Dspring.profiles.active=dev
  • 1
  • 2

7.SpringBoot配置文件位置

springBoot可以默認讀取的文件有兩種,一個是application.properties以及application.yml文件
可是這兩個文件能夠存放在哪個位置,就是在

  • file:項目根目錄/config
  • file:項目根目錄
  • classpath:項目根目錄/config
  • classpath:項目根目錄
    file與classpath的區別就是
  • file指普通目錄
  • classpath指構建路徑(構建路徑的文件夾上面有一個小標識)
    若是項目配置衝突,優先級從上往下

8.外部配置文件以及加載順序問題

配置項目運行名

在主配置文件application.properties中加入:

server.servlet.context-path=/springBoot
  • 1

注意:此處的springBoot就是新加入的項目名,在未加入以前訪問是這樣的:

http://localhost:8888/HelloWord?name=zhuxu
  • 1

加了以後就變成了這樣的:

http://localhost:8888/springBoot/HelloWord?name=zhuxu
  • 1

如何使用外部的配置文件

好比說在個人這個路徑下C:\Users\17732\Desktop\test\application.properties有一個application.properties文件,那麼怎麼使用裏面的配置:

右單擊 ->Run As->RunConfigurations->Arguments->在裏面輸入--spring.config.location=路徑名
好比:--spring.config.location=C:\Users\17732\Desktop\test\application.properties
  • 1
  • 2

若是內部外部配置有衝突,優先選擇外部的

接着學習一下如何經過cmd命令調用外部配置文件

java -jar HelloWord-0.0.1-SNAPSHOT.jar --spring.config.location=C:\Users\17732\Desktop\test\application.properties
  • 1

設置某一個參數,仍是按照這個步驟(右單擊 ->Run As->RunConfigurations->Arguments)到Arguments下
好比說只更改端口:–server.port=8882

9.springBoot的日誌處理

目前springBoot用的是slf4j以及logback日誌

具體如何使用日誌參照下面代碼:

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloWordApplicationTests {
	Logger logger=LoggerFactory.getLogger(HelloWordApplicationTests.class);
	@Test
	public void testLog() {
		logger.trace("測試Logger_Trace");
		logger.debug("測試Logger_debug");
		logger.info("測試Logger_Info");
		logger.warn("測試Logger_warn");
		logger.error("測試logger_error");
	}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

可是在測試時發現只能輸出info warn 以及error中的內容,其餘的內容均爲輸出,這是因爲日誌級別的問題
日誌級別有:

trace debug info warn error fail off
  • 1

其中默認的級別是 info,只打印info之後的,而Info之前的不給予打印

下面繼續認識一下如何自定義日誌級別

在主配置文件application.properties中設置:

logging.level.com.test.HelloWord=debug
其中com.test.HelloWord是主配置類的包名
  • 1
  • 2

這樣的話就把日誌的默認級別也就是最低級別調到debug

繼續深刻————如何把日誌輸出信息打印到文件中呢

在主配置文件application.properties中設置:
logging.file=D:/program/springBoot/HelloWord/log/springBoot.Log
這樣的話就能夠把日誌信息加入到上面目錄下的springBoot.Log文件中
固然還有logging.path=D:/
這樣的話就直接把日誌輸出指定的文件夾中,默認的文件名是spring.log
  • 1
  • 2
  • 3
  • 4
  • 5

下面接着看如何更改日誌輸出的格式

指定日誌顯示格式:

  • 1.日誌顯示在控制檯:
在主配置文件application.properties中設置:
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} -%msg%n
  • 1
  • 2

下面解釋一下上面這串代碼的意思:

  • %d:日期時間
  • %thread:打印線程名
  • %-5level:顯示日誌級別,-5表示從左顯示5個字符寬度
  • %logger{50}:設置日誌寬度,50表示最多隻能有50個日誌
  • %msg:日誌消息
  • %n:表示顯示完自動換行
  • 2.日誌顯示在文件中:
在主配置文件application.properties中設置:
logging.pattern.file=%d{yyyy-MM-dd} ** [%thread] **  %-5level **  %logger{50} **  %msg%n
  • 1
  • 2

10.springBoot處理web靜態資源

1.先pom.xml文件中導入jquery,Bootstrap等靜態資源文件:

  • jquery:
<dependency>
		<groupId>org.webjars</groupId>
		<artifactId>jquery</artifactId>
		<version>3.3.1-1</version>
	</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • BootStrap
<!-- https://mvnrepository.com/artifact/org.webjars/bootstrap -->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>bootstrap</artifactId>
    <version>4.1.3</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

下面簡單的進行對jquery.js進行訪問:

http://localhost:1234/zhiyi/webjars/jquery/3.3.1-1/jquery.js
  • 1

注意:開始的是從webjars開始的

下面在看一下怎麼引入本身寫的靜態資源,本身寫的靜態資源放在哪裏

  • 首先自定義的資源只能放在構建路徑下的static或者resources目錄下面
  • 在訪問靜態資源時不用寫前綴目錄,好比有一個文件a.html在resources目錄下,那麼在訪問時:
http://localhost:1234/zhiyi/Hello.html
  • 1

歡迎頁的實現:

在任意靜態資源目錄下,只要文件名叫作index.html,它就是主頁,直接訪問便可:

http://localhost:1234/zhiyi
  • 1

下面接着看看如何更改網站的logo,任何一個網站中的logo都有一個固定名字:favicon.ico

那麼如何進行更改favicon.ico呢

咱們只須要將favicon.ico放在任何靜態資源目錄中便可
如何自定靜態資源位置:

在主配置文件application.properties中設置:
spring.resources.static-locations=classpath:/res/
  • 1
  • 2

而後在src/main/resources下建立對應的res目錄,這樣的話靜態資源目錄除了默認的resources以及static目錄,res如今也是靜態資源目錄了
一樣訪問的時候也不須要加前綴res,直接輸入文件名便可:

http://localhost:1234/zhiyi/res.html
  • 1

若是建立多個資源路徑就這樣:

spring.resources.static-locations=classpath:/res/ ,classpath:/img/
  • 1

注意:一旦自定義了,默認的靜態資源文件夾就會所有失效

11.引入模板引擎thymeleaf

上面學習瞭如何引入靜態資源,那麼如何引入動態資源

springBoot是不支持動態頁面jsp,可是如何來替換jsp頁面呢,那麼就使用咱們的動態模板引擎thymeleaf
那麼到底什麼是模板引擎:
模板引擎就是將一個網友分爲兩部分:

  • 模板
  • 數據
    如何引用這個數據引擎:
在pom文件中添加依賴,這個依賴能夠在maven裏面直接搜索,也能夠在這個網址:

https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#using-boot-starter

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf</groupId>
			<artifactId>thymeleaf-spring5</artifactId>
		</dependency>
		<dependency>
			<groupId>org.thymeleaf.extras</groupId>
			<artifactId>thymeleaf-extras-java8time</artifactId>
		</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

導入以後咱們來研究第一個問題:引入thymeleaf 代碼應該往哪裏寫

thymeleaf的代碼所有放在構建路徑(src/main/resources/)下的templete目錄下
下面先看一個模板:
templete目錄下的html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymleaf</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head> 
<body>
<p th:text="${welcome}">Welcome to thymeleaf!</p>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

先看一下上面這個代碼片斷,其餘的都是模板,之後直接拿着用,可是p中有一個th:text="${welcome},會優先顯示welcome中的內容
那麼總結一下:th:就是替換的意思,好比:

<p id="aaa" class="aaa" th:id="${welcome}" th:class="${welcome}"  th:text="${welcome}">Welcome to thymeleaf!</p>
  • 1

那麼若是${welcome}中有值,那麼就就會有優先使用welcome中的值
在寫一個controller:

@Controller
public class BootController {
	@RequestMapping("/wecome")
	public String wecome(Map<String, Object> map) {
		map.put("welcome", "welcome_Thymeleaf");
		return "result";
	}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

th後面到底能夠存放哪些內容呢:

Order Feature Attributes
1 Fragment inclusion th:insert th:replace
2 Fragment iteration
3 Conditional evaluation th:if th:unless th:switch th:case
4 Local variable definition th:object th:with
5 General attribute modification th:attr th:attrprepend th:attrappend
6 Specific attribute modification th:value th:href th:src …
7 Text (tag body modification) th:text th:utext
8 Fragment specification th:fragment
9 Fragment removal th:remove

下面重點講一下 th:text,th:untext

  • th:text:表示轉義,何爲轉義,舉一個小小的例子:
th:text="<h1>hello</h1>"
th:untext="<h1>hello</h1>"
  • 1
  • 2

第一個顯示的是大大的標題hello,而第二個顯示的是‘《h1》hello《/h1》’
下面寫一個關於th:each的用法:
html頁面:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymleaf</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet"
	href="webjars/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet"
	    href="webjars/bootstrap/4.1.3/css/css/bootstrap-theme.min.css">
<script src="webjars/jquery/3.3.1-1/jquery.js"></script>
<script src="webjars/bootstrap/4.1.3/css/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
		<table class="table table-striped table-bordered">
			<thead>
				<tr>
					<th>姓名</th>
					<th>年齡</th>
				</tr>
			</thead>
			<tbody>
				<tr th:each="student : ${Students}">
					<td th:text="${student.name}">姓名</td>
					<td th:text="${student.age}">年齡</td>
				</tr>
			</tbody>
		</table>
	</div>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

對應的controller:

@Controller
public class BootController {
	@RequestMapping("/wecome")
	public String wecome(Map<String, Object> map) {
		map.put("welcome", "welcome_Thymeleaf");
		List<Student> lStudents = new ArrayList<Student>();
		lStudents.add(new Student("zx", 21));
		lStudents.add(new Student("zx1", 22));
		lStudents.add(new Student("zx3", 23));
		lStudents.add(new Student("zx4", 24));
		map.put("Students", lStudents);
		return "result";
	}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

對應的Po:

public class Student {
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public Student() {
		super();
	}
	public Student(String n,Integer a) {
		super();
		this.name=n;
		this.age=a;
	}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

12.SpringBoot整合外置tomcat以及使用jsp開發

springBoot是不支持jsp開發的,由於jsp頁面須要打成war包部署到tomcat,可是springBoot是不用打成war包就能運行,這個時候就須要使用外置的tomcat

下面接着講一個maven的小知識:

若是pom中的依賴中有provided字樣,那麼在打包時不會將q以對應的插件或者文件一塊兒打包

接着進入咱們的主題:如何使用外置的tomcat,參考 點擊此處
而後進行下面幾個步驟:

  • 1.創建基本的web目錄結構:在src/main/webapp裏面創建一個目錄:WEB-INF
  • 2.在src/main/webapp下面寫jsp頁面
    下面講一下如何在springBoot中配置視圖解析器;
    在主配置文件application.properties中添加以下代碼:
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
  • 1
  • 2

index.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
Hello ${requestScope.name} Welcome to Index.jsp
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Controller:

@Controller
public class WebController {
	@RequestMapping("/welcome")
	public String welcome(Map<String, Object>map) {
		map.put("name", "朱旭");
		return "index";
	}}
相關文章
相關標籤/搜索