springboot&freemarker
FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。
上一篇我们介绍了springboot2.x整合thymeleaf,此篇我们来介绍一下springboot如何使用freemarker。
一
目标
基于springboot2.x,整合freemarker模板引擎,并展示用户的基本信息。
二
springboot整合freemarker
1:引入依赖
springboot整合freemarker除了引入基础依赖之外,还要引入spring-boot-starter-freemarker。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- freemark --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
不需要其他额外的配置,springboot将引入所有必须的依赖并且注入所有必需的配置来使用freemarker。
2:修改application.properties
springboot会去默认的路径src/main/resources/templates下寻找html模板文件。
spring.freemarker.template-loader-path=classpath:/templates
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
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.suffix=.ftl
3:编码实现
用户信息实体类:
@Setter @Getter @ToString public class User implements Serializable { private Long id; // 主键ID private String name; // 姓名 private Date createTime; private Integer sex; private Integer age; }
编写IndexController处理简单的用户信息查询请求:
@Controller @Slf4j public class IndexController { @GetMapping("/user/{id}") public String queryUser(@PathVariable("id") Long id, Model model) { User user = new User(); user.setId(id); user.setName("Typhoon"); user.setAge(28); user.setSex(1); model.addAttribute("user",user); return "/index"; } }
在resources目录下创建templates文件夹并新建index.ftl文件:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>freemark</title> </head> <body> <p> 你好 ${user.name}</p> <p> 性别: <#if user.sex==1> 男 <#elseif user.sex==0> 女 <#else> 保密 </#if> </p> <p> 年龄 ${user.age}</p> </body> </html>
编写应用启动类:
@SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
4:启动应用&测试
启动应用,浏览器输入http://localhost:8080/user/1:
总结
此篇中,我们介绍了如何为springboot应用程序整合freemarker。希望能够带来帮助。
本文分享自 PersistentCoder 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!