10.4、spring boot的web应用——支持freemarker模板视图

来源:互联网 发布:减肥午餐吃什么知乎 编辑:程序博客网 时间:2024/06/03 21:16

目前,在spring boot中应用比较多的是freemarker模板,若想在spring boot的web中支持freemarker视图,需要在pom.xml中导入freemarker的依赖。

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

下面通过示例演示freemarker应用

一、示例1

1、freemarker模板视图默认是放在/templates/目录下的,所以在/src/main/resources/目录下创建/templates/目录,freemarker模板视图放在该目录下即可。freemarker文件格式为 .ftl
这里写图片描述

2、创建控制视图类

package com.lzj.spring.boot;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;/* * 1、不要用@RestController注解,要用@Controller注解。因为@RestController注解中包含@ResponseBody注解 * 2、要导入freemarker的依赖包,删掉jsp的依赖包 * 3、ftl文件默认放在src/main/resources下的templates目录下,即classpath:/templates/ *  * */@Controllerpublic class MyFreeMarker {    /*视图方法响应请求后,返回login.ftl视图*/    @RequestMapping("/login")    public String login(){        return "login";    }}

在templates目录下创建login.ftl视图,内容为:

<h1>This is login page</h1>

3、启动类为:

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

运行启动类,在浏览器中输入http://localhost:8080/login后,控制视图方法响应请求后,返回“login”字符串,视图解析器解析为login.ftl视图,并送到浏览器显示。
这里写图片描述

二、示例2:更改freemarker模板视图的默认存放位置

freemarker文件默认是存放在classpath:/templates目录下的,如果想改变默认的存放位置,例如想放在classpath:/ftl目录下,可以在application.properties文件中配置如下:

spring.freemarker.templateLoaderPath=classpath:/ftl

下面创建控制视图类:

@Controllerpublic class MyFreeMarker {    /*可以更改ftl文件默认存放的位置     * 只需要在application.properties中加入:spring.freemarker.templateLoaderPath=classpath:/ftl     * 该配置可以从spring-boot-autoconfigure的jar包中的org.springframework.boot.autoconfigure.freemarker中的     * FreeMarkerProperties类中可以看到     * */    @RequestMapping("/reg")    public String configPath(){        return "reg";    }

然后在/ftl目录下创建reg.ftl文件,内容为:

<h1>This is REG page</h1>

运行启动类,在浏览器中输入http://localhost:8080/reg,视图控制方法响应请求后,返回“reg”字符串,视图解析器把该字符串解析为reg.ftl,然后送回浏览器显示。

三、示例3:向ftl视图中传入参数

创建视图控制类

@Controllerpublic class MyFreeMarker {    /*通过Model把参数加入响应的ftl视图中,与前面博客中介绍的jsp响应相似*/    @RequestMapping("/logout")    public String logout(Model model){        model.addAttribute("username", "lzj");        model.addAttribute("password", "123456");        return "logout";    }

在templates目录下创建logout.ftl文件,内容为:

<h1>This is LOGOUT page</h1><p>username:${username}</p><p>password:${password}</p>

运行启动类,在浏览器中输入http://localhost:8080/logout,控制视图方法响应后,返回“logout”字符串,默认的视图解析器字符串解析为logout.ftl视图,并送浏览器显示。
这里写图片描述