在pom.xml中引入freemaker
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
关闭freemarker缓存
# FreeeMarker 模板引擎配置
spring.freemarker.allow-request-override=false
spring.freemarker.cache=false
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.request-context-attribute=
#spring.freemarker.settings.*=
#spring.freemarker.suffix=.ftl
#spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved
编写模板文件hello.ftl
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello , ${name}</h1>
</body>
</html>
编写访问文件的controller
package com.example.demo.controller;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* 注意:
* 1.在Themeleaf模板文件 中,标签是需要闭合的,3.0之前是需要闭合的
* 2.themeleaf 3.0+是可以不强制要求闭合的
* 3.模板引擎可以同时存在多个,例如themeleaf和freemarker同时存在
* @author Lidy
*
*/
@Controller
@RequestMapping("/templates")
public class TemplatesController {
/**
* 映射地址:/templates/hello
* @return
*/
@RequestMapping("/hello")
public ModelAndView hello(Map<String,Object> map){
ModelAndView mv = new ModelAndView("hello");
map.put("name", "道哥");
return mv;
}
@RequestMapping("/helloFtl")
public String helloFtl(Map<String,Object> map){
map.put("name", "道哥");
return "hello";
}
}
浏览器访问
Paste_Image.png
网友评论