Spring Boot 整合Freemarker
    		       		warning:
    		            这篇文章距离上次修改已过428天,其中的内容可能已经有所变动。
    		        
        		                
                Spring Boot整合Freemarker的步骤如下:
- 在pom.xml中添加Freemarker的依赖:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>- 在application.properties或application.yml中配置Freemarker的设置(可选):
# application.properties 示例
spring.freemarker.template-loader-path=classpath:/templates
spring.freemarker.suffix=.ftl
spring.freemarker.charset=UTF-8
spring.freemarker.enabled=true
spring.freemarker.cache=false
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.request-context-attribute=request
spring.freemarker.order=- 创建Freemarker模板文件,通常放在src/main/resources/templates目录下,以.ftl为文件后缀名。
例如,创建一个名为hello.ftl的模板文件:
<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>- 创建一个Controller来使用Freemarker渲染模板:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class HelloController {
 
    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello, Freemarker!");
        return "hello"; // 对应模板文件名称,不需要添加.ftl后缀
    }
}以上步骤完成后,启动Spring Boot应用,并访问/hello路径,Freemarker就会渲染hello.ftl模板并显示页面。
评论已关闭