(9) spring boot使用freemarker模板引擎


1. 項目結構



2. 在pom.xml文件中添加freemarker依賴


<!-- 添加freemarker依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

3. 在application.properties中添加freemarker配置

spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
#spring.freemarker.prefix=
spring.freemarker.suffix=.ftl

4. 在src/main/resources/templates/添加testFtl.ftl,內容如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
    Hello,${nameKey}
</body>
</html>

5. 編寫TemplatesController

package com.lanhuigu;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 註意: [email protected],[email protected],用的是spring MVC邏輯,
* 在spring MVC中,需要在spring mvc配置的視圖解析器中指定視圖文件位置,spring boot使用
* freemarker等於將視圖地址默認在src/main/resources/templates下瞭
*/
@Controller
@RequestMapping("/templates")
public class TemplatesController {

@RequestMapping("/helloFtl")
    public String helloFtl(Map<String,Object> map) {
        map.put("nameKey", "freemarker");
        return "testFtl";
    }
}

6.

編寫啟動類App

package com.lanhuigu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* Hello world!
* 啟動類
*/
@SpringBootApplication
public class App {

public static void main( String[] args ) {
/*System.out.println( "Hello World!" );*/
SpringApplication.run(App.class, args);
}
}

7. 啟動服務訪問,默認端口8080


0 個評論

要回覆文章請先登錄註冊