什么叫模板引擎
1、浏览器请求web服务器
2、服务器渲染页面,渲染的过程就是向jsp页面(模板)内填充数据(模型)。
3、服务器将渲染生成的页面返回给浏览器。
所以模板引擎就是:模板+数据=输出,Jsp页面就是模板,页面中嵌入的jsp标签就是数据,两者相结合输出html网页。
Freemarker快速入门
添加Freemarker与SpringBoot的整合包
XML <!-- Spring Boot 对结果视图 Freemarker 集成 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> |
在nacos为内容管理接口层配置freemarker,公用配置组新加一个freemarker-config-dev.yaml
配置信息如下:
spring: freemarker: enabled: true cache: false #关闭模板缓存,方便测试 settings: template_update_delay: 0 suffix: .ftl #页面模板后缀名 charset: UTF-8 template-loader-path: classpath:/templates/ #页面模板位置(默认为 classpath:/templates/) resources: add-mappings: false #关闭项目中的静态资源映射(static、resources文件夹下的资源) |
配置文件中添加freemarker-config-dev.yaml
添加模板,在resources下创建templates目录,添加test.ftl模板文件
HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Hello World!</title> </head> <body> Hello ${name}! </body> </html> |
编写controller方法,准备模型数据
Java package com.xuecheng.content.api;
import org.bouncycastle.math.raw.Mod; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
@Controller public class FreemarkerController {
@GetMapping("/testfreemarker") public ModelAndView test(){
ModelAndView modelAndView = new ModelAndView(); //设置模型数据 modelAndView.addObject("name","小明"); //设置模板名称 modelAndView.setViewName("test"); return modelAndView; }
} |
浏览器访问该接口就可以看到该门户了