之前在Eclipse里寫了個Spring Boot響應jsp的小demo,后來發現打成jar包導出之后找不到jsp文件了。經過在網上查閱信息與資料,發現Spring Boot對于jsp的支持其實是不好的,而且在一些書中和官方都明確表示沒有辦法支持在jar包中打入jsp文件。雖然也有些朋友發現將Spring Boot的版本降到1.4.2,通過插件可以打進去并且訪問到。但其實已經說明了一個問題,也就是既然選用了Spring Boot,就不要再用jsp了。
講了那么多,現在來分享一下Spring Boot結合thymeleaf的實例。
由于在另一篇隨筆里已經詳述過如何在Eclipse里構建一個Spring Boot工程,這里就不再細說。
大致的目錄結構如下
pom中的相關依賴如下
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>
application.properties中相關配置如下
server.port=8080 server.session.timeout=10 spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.content-type=text/html spring.thymeleaf.cache=false
入口類如下
package com.thymeleaf;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);} }
ctrl層demo如下
package com.thymeleaf.controller;import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;@Controller public class DemoController {@RequestMapping("/")public String index() {return "index";} }
然后啟動,在瀏覽器中輸入localhost:8080即可跳轉到index.html了
?