最近看的springboot 在網上看到了不少教程,跳轉有不少方法,在這裏,我記錄了三種,供你們參考
spring boot 在springmvc的視圖解析器方面就默認集成了ContentNegotiatingViewResolver和BeanNameViewResolver,在視圖引擎上就已經集成自動配置的模版引擎,以下:
1. FreeMarker
2. Groovy
3. Thymeleaf
4. Velocity (deprecated in 1.4)
6. Mustache
JSP技術spring boot 官方是不推薦的,緣由有三:
1. 在tomcat上,jsp不能在嵌套的tomcat容器解析即不能在打包成可執行的jar的狀況下解析
2. Jetty 嵌套的容器不支持jsp
3. Undertow
spring Boot加載html默認到resources/templates裏尋找:html
Thymeleafweb
首先 增長依賴:spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
1)templates目錄
如 index.html.
須要注意的是:自動生成的html, 是不全的,注意區分。瀏覽器
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Title</title> </head> <body> Hello world! </body> </html>
Controller進行跳轉,
提供了兩種方式,tomcat
1)是直接返回字符串,字符串爲html的名字,視圖會自動解析。
2)是利用ModelAndView,如圖:springboot
@Controller public class TestController { @RequestMapping("/mvc1") public String mvc1(){ return "index"; } @RequestMapping("/mvc2") @ResponseBody public ModelAndView mvc2(){ ModelAndView mv = new ModelAndView("index"); return mv; } }
此時測試
localhost:8080/mvc1
成功跳轉界面mvc
FreeMarker詳解
首先,增長依賴,freemarker和devtools必須有,還有web,這個自動就有,若是沒有記得加上
<!--加載靜態文件模板第二種方法,freemarker,必定記得加devtools-->app
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
1)這裏寫圖片描述
在這裏首先是demo.ftl,必定注意是ftl結尾。jsp
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>Insert title here</title> </head> <body> 請看說明:${descrip} <br /> </body> </html>
2)TestControllerspring-boot
@Controller public class TestController { @RequestMapping("/demo") public String demo(Map<String, Object> map) { map.put("descrip", "It's a springboot integrate freemarker's demo!!!!"); return "demo"; } }
3)瀏覽器測試
local:8080/demo
完美成功。固然 還有最重要的jsp。不推薦用
原文:http://www.javashuo.com/article/p-hnpkxdlf-nd.html