Spring Boot 頁面跳轉視圖解析Thymeleaf和FreeMarker詳解


最近看的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里尋找:


Thymeleaf


首先 增加依賴:

   <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進行跳轉,

提供了兩種方式,

1)是直接返回字符串,字符串為html的名字,視圖會自動解析。
2)是利用ModelAndView,如圖:

@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
成功跳轉界面


FreeMarker詳解

首先,增加依賴,freemarker和devtools必須有,還有web,這個自動就有,如果沒有記得加上

<!--加載靜態文件模板第二種方法,freemarker,一定記得加devtools-->

  <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結尾。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Insert title here</title>
</head>
<body>
請看說明:${descrip} <br />
</body>
</html>

 


2)TestController

@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。不推薦用

原文:https://blog.csdn.net/qq_37355731/article/details/77049804


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM