web应用中使用freemarker

springboot整合freemarker,首先加入依赖:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/> 
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
        <!--发现spring-boot-starter-freemarker依赖中包括spring-boot-starter-web依赖-->
      <dependency>
           <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
      </dependency>
</dependencies>

定义Controller类

@Controller
public class UserController {

    @GetMapping("/reg")
    public String reg(){
        return "reg";
    }

    @GetMapping("/logout")
    public String logout(Model model){
        model.addAttribute("username","zhihao.miao");
        model.addAttribute("logout","true");
        return "logout";
    }
}

启动类:

package com.zhihao.miao;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

因为springboot整合freemarker默认的会读取classpath:/templates/下的模版文件,所以一般我们将模版文件放入到classpath:/templates/下即可。
reg.ftl文件内容:

package com.zhihao.miao;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

logout.ftl:

<h1>logout page</h1>
<h1>username is ${username}</h1>
<h1>logout is ${logout}</h1>

启动Application类并启动

也可以修改模版文件的位置,可以使用

spring.freemarker.templateLoaderPath=classpath:/ftl

将上面二个模版文件放在ftl文件夹下重新测试一下即可。

源码查看:
org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容