springboot整合freemarker

freemarker简介

Freemarker 模版后缀为 .ftl(FreeMarker Template Language)。FTL 是一种简单的、专用的语言,它不是像 Java 那样成熟的编程语言。在模板中,你可以专注于如何展现数据, 而在模板之外可以专注于要展示什么数据。

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

工程创建完成后,在 org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration 类中,可以看到关于 Freemarker 的自动化配置:

@Configuration
@ConditionalOnClass({ freemarker.template.Configuration.class, FreeMarkerConfigurationFactory.class })
@EnableConfigurationProperties(FreeMarkerProperties.class)
@Import({ FreeMarkerServletWebConfiguration.class, FreeMarkerReactiveWebConfiguration.class,
                FreeMarkerNonWebConfiguration.class })
public class FreeMarkerAutoConfiguration {
}

从这里可以看出,当 classpath 下存在 freemarker.template.Configuration 以及 FreeMarkerConfigurationFactory 时,配置才会生效,也就是说当我们引入了 Freemarker 之后,配置就会生效。但是这里的自动化配置只做了模板位置检查,其他配置则是在导入的 FreeMarkerServletWebConfiguration 配置中完成的。那么我们再来看看 FreeMarkerServletWebConfiguration 类,部分源码如下:

@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass({ Servlet.class, FreeMarkerConfigurer.class })
@AutoConfigureAfter(WebMvcAutoConfiguration.class)
class FreeMarkerServletWebConfiguration extends AbstractFreeMarkerConfiguration {
        protected FreeMarkerServletWebConfiguration(FreeMarkerProperties properties) {
                super(properties);
        }
        @Bean
        @ConditionalOnMissingBean(FreeMarkerConfig.class)
        public FreeMarkerConfigurer freeMarkerConfigurer() {
                FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
                applyProperties(configurer);
                return configurer;
        }
        @Bean
        @ConditionalOnMissingBean(name = "freeMarkerViewResolver")
        @ConditionalOnProperty(name = "spring.freemarker.enabled", matchIfMissing = true)
        public FreeMarkerViewResolver freeMarkerViewResolver() {
                FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
                getProperties().applyToMvcViewResolver(resolver);
                return resolver;
        }
}

我们来简单看下这段源码:

1.@ConditionalOnWebApplication 表示当前配置在 web 环境下才会生效。
2.ConditionalOnClass 表示当前配置在存在 Servlet 和 FreeMarkerConfigurer 时才会生效。
3.@AutoConfigureAfter 表示当前自动化配置在 WebMvcAutoConfiguration 之后完成。
4.代码中,主要提供了 FreeMarkerConfigurer 和 FreeMarkerViewResolver。
5.FreeMarkerConfigurer 是 Freemarker 的一些基本配置,例如 templateLoaderPath、defaultEncoding 等
6.FreeMarkerViewResolver 则是视图解析器的基本配置,包含了viewClass、suffix、allowRequestOverride、allowSessionOverride 等属性。
另外还有一点,在这个类的构造方法中,注入了 FreeMarkerProperties:

@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
        public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
        public static final String DEFAULT_PREFIX = "";
        public static final String DEFAULT_SUFFIX = ".ftl";
        /**
         * Well-known FreeMarker keys which are passed to FreeMarker's Configuration.
         */
        private Map<String, String> settings = new HashMap<>();
}

FreeMarkerProperties 中则配置了 Freemarker 的基本信息,例如模板位置在 classpath:/templates/ ,再例如模板后缀为 .ftl,那么这些配置我们以后都可以在 application.properties 中进行修改。

如果我们在 SSM 的 XML 文件中自己配置 Freemarker ,也不过就是配置这些东西。现在,这些配置由 FreeMarkerServletWebConfiguration​ 帮我们完成了。

Controller层

package com.java.freemarker.controller;

import com.java.freemarker.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author :shawn
 * @create :2020-06-22 21:45:00
 */
@Controller
public class UserController {

    @GetMapping("/user")
    public String user(Model model)
    {
        List<User> users = new ArrayList<>();
        Random random = new Random();
        for (int i=0;i<10;i++)
        {
            User user = new User();
            user.setId((long)i);
            user.setUsername("javagirl>>"+i);
            user.setAddress("www.javagirl.com>>"+i);
            user.setGender(random.nextInt(3));//生成随机数
            users.add(user);

        }
        model.addAttribute("users",users);
        return "user";
    }
}

user.ftl

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<#include './header.ftl'>
<table border="1">
    <tr>
        <td>编号</td>
        <td>用户名</td>
        <td>用户地址</td>
    </tr>
    <#list users as u>
    <#if u.id=4>
        <#break>
    </#if>
        <tr>
            <td>${u.id}</td>
            <td>${u.username}</td>
            <td>${u.address}</td>
            <td>
               <#-- <#if u.gender==1>
                    男
                <#elseif u.gender==0>
                    女
                <#else>
                    未知
                </#if>-->
                <#switch u.gender>
                    <#case 0><#break>
                    <#case 1><#break>
                    <#default>未知
                </#switch>
            </td>
        </tr>
    </#list>
</table>
</body>
</html>

运行结果
在这里插入图片描述
其他配置
如果我们要修改模版文件位置等,可以在 application.properties 中进行配置:

spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
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.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/

配置文件按照顺序依次解释如下:
1.HttpServletRequest的属性是否可以覆盖controller中model的同名项
2.HttpSession的属性是否可以覆盖controller中model的同名项
3.是否开启缓存
4.模板文件编码
5.是否检查模板位置
6.Content-Type的值
7.是否将HttpServletRequest中的属性添加到Model中
8.是否将HttpSession中的属性添加到Model中
9.模板文件后缀
10.模板文件位置

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Freemarker是一种模板引擎,可以将数据和模板进行整合生成输出内容。SpringBoot提供了对Freemarker的支持,可以很方便地整合Freemarker。 1. 添加依赖 在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> ``` 2. 配置文件 在application.properties文件中添加以下配置: ```properties spring.freemarker.template-loader-path=classpath:/templates/ spring.freemarker.cache=false ``` - template-loader-path:模板文件的路径,这里设置为classpath:/templates/,表示在项目的classpath下的templates目录中查找模板文件。 - cache:是否开启模板缓存,这里设置为false,表示关闭缓存。 3. 创建模板文件 在classpath:/templates/目录下创建一个名为index.ftl的模板文件,内容如下: ```html <!DOCTYPE html> <html> <head> <title>SpringBoot整合Freemarker</title> </head> <body> <h1>${message}</h1> </body> </html> ``` 4. 创建控制器 创建一个名为IndexController的控制器,代码如下: ```java @Controller public class IndexController { @RequestMapping("/") public String index(Model model) { model.addAttribute("message", "Hello, World!"); return "index"; } } ``` 该控制器中,使用@RequestMapping注解指定了请求路径为/,并将一个名为message的属性值设置为“Hello, World!”,然后返回了index作为视图名称。由于配置了spring.freemarker.template-loader-path=classpath:/templates/,所以SpringBoot会在classpath:/templates/目录下查找名为index的模板文件,并将模板文件中的${message}替换为“Hello, World!”。 5. 运行程序 启动应用程序,访问http://localhost:8080/,可以看到页面中显示了“Hello, World!”的字样。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值