引言
在傳統(tǒng)的web開發(fā)中通常使用jsp頁(yè)面,首先需要在pom文件中引入springmvc相關(guān)的包,然后寫springmvc的配置文件(包括訪問(wèn)資源的路徑解析),之后還需再web.xml中配置訪問(wèn)路由。這無(wú)疑太麻煩了,每次開發(fā)前都需要編寫大量的配置文件。
html">springboot為此提供了高效便捷的解決方案,只需再pom.xml中添加web開發(fā)的依賴,便可進(jìn)行web開發(fā),省去了繁瑣的配置步驟。
下面為web開發(fā)引入的依賴
1
2
3
4
|
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> |
正文
那么在springboot中如果需要使用頁(yè)面該怎么做呢?springboot不推薦使用jsp,因?yàn)閖sp在springboot中有諸多限制,具體限制這里就不展開說(shuō)了,大家感興趣可以去網(wǎng)上查閱。springboot中推薦使用thymeleaf模板,使用html作為頁(yè)面展示。那么如何通過(guò)controller來(lái)訪問(wèn)來(lái)訪問(wèn)html頁(yè)面呢?
1.在pom.xml文件中添加thymeleaf依賴
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<dependencies> <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> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency> </dependencies> |
2.在application.yml中添加訪問(wèn)請(qǐng)求配置
1
2
3
4
5
6
|
##thymeleaf頁(yè)面模板配置 spring: mvc: view: prefix: / suffix: .html |
springboot中默認(rèn)resources中static文件夾存放靜態(tài)資源,如js文件、css文件、圖片等等。templates文件夾中存放html頁(yè)面。
3.在templates文件夾中創(chuàng)建hello.html
1
2
3
4
5
6
7
8
9
10
|
<!doctype html> <html lang= "en" > <head> <meta charset= "utf-8" /> <title>title</title> </head> <body> hello world </body> </html> |
4.編寫controller
1
2
3
4
5
6
7
8
9
10
|
/** * created by tomthy on 2018/5/10 */ @controller public class contentcontroller { @getmapping ( "/hello" ) private string helloworld(){ return "hello" ; } } |
注意:不要使用@restcontroller注解,@restcontroller注解是@responsebody和@controller的集合體,使用@restcontroller注解會(huì)默認(rèn)返回?cái)?shù)據(jù),而不會(huì)請(qǐng)求到頁(yè)面。
5.在瀏覽器中輸入請(qǐng)求地址
輸入地址:http://localhost:8080/hello 便可請(qǐng)求到hello.html頁(yè)面。
6.靜態(tài)資源的訪問(wèn)
html頁(yè)面中使用到靜態(tài)資源時(shí)(如圖片),直接使用<script type="text/javascript" src="/js/wangeditor.js"></script>。js為static下的文件夾。
7.項(xiàng)目目錄
總結(jié)
以上所述是小編給大家介紹的springboot使用thymeleaf模板訪問(wèn)html頁(yè)面,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://www.jianshu.com/p/bd7a821515ec