小編給大家分享一下springboot使用thymeleaf模板訪問html頁面的案例,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
引言
在傳統的web開發中通常使用jsp頁面,首先需要在pom文件中引入springmvc相關的包,然后寫springmvc的配置文件(包括訪問資源的路徑解析),之后還需再web.xml中配置訪問路由。這無疑太麻煩了,每次開發前都需要編寫大量的配置文件。
springboot為此提供了高效便捷的解決方案,只需再pom.xml中添加web開發的依賴,便可進行web開發,省去了繁瑣的配置步驟。
下面為web開發引入的依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
正文
那么在springboot中如果需要使用頁面該怎么做呢?springboot不推薦使用jsp,因為jsp在springboot中有諸多限制,具體限制這里就不展開說了,大家感興趣可以去網上查閱。springboot中推薦使用thymeleaf模板,使用html作為頁面展示。那么如何通過Controller來訪問來訪問html頁面呢?
1.在pom.xml文件中添加thymeleaf依賴
<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中添加訪問請求配置
##thymeleaf頁面模板配置 spring: mvc: view: prefix: / suffix: .html
springboot中默認resources中static文件夾存放靜態資源,如js文件、css文件、圖片等等。templates文件夾中存放html頁面。
3.在templates文件夾中創建hello.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> hello world </body> </html>
4.編寫Controller
/** * Created by Tomthy on 2018/5/10 */ @Controller public class ContentController { @GetMapping("/hello") private String helloWorld(){ return "hello"; } }
注意:不要使用@RestController注解,@RestController注解是@ResponseBody和@Controller的集合體,使用@RestController注解會默認返回數據,而不會請求到頁面。
5.在瀏覽器中輸入請求地址
輸入地址:http://localhost:8080/hello便可請求到hello.html頁面。
6.靜態資源的訪問
html頁面中使用到靜態資源時(如圖片),直接使用<script type="text/javascript" src="/js/wangEditor.js"></script>。js為static下的文件夾。
7.項目目錄
看完了這篇文章,相信你對“springboot使用thymeleaf模板訪問html頁面的案例”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。