45

SpringBoot系列:Spring Boot使用模板引擎FreeMarker

 4 years ago
source link: https://www.tuicool.com/articles/UzQJZfu
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一、Java模板引擎

模板引擎(这里特指用于Web开发的模板引擎)是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。

在java中,主要的模板引擎有JSP、Thymeleaf、FreeMarker、

Velocity等。

虽然随着前后端分离的崛起和流行,模板引擎已遭受到冷落,但不少旧项目依然使用java的模板引擎渲染界面,而偶尔自己写一些练手项目,使用模板引擎也比起前后端分离要来的快速。

本系列会分别讲解SpringBoot怎么集成JSP、Thymeleaf和FreeMarker,至于Velocity,高版本的SpringBoot已经不支持Velocity了,这里也就不进行讲解了。

而这一篇,主要讲解Spring Boot如何集成FreeMarker。

一、Spring Boot集成FreeMarker

首先我们要引入依赖,除了核心的web依赖外,只需引入freemarker的statrer即可。

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

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

然后就是配置文件了。主要配置spring.freemarker节点下的视图文件目录template-loader-path以及文件后缀suffix,如果是本地开发,cache可以设置为false关闭缓存,避免修改文件后需要重新启动服务。

server:
  port: 10900

spring:
  profiles:
    active: dev
  freemarker:
    enabled: true #是否启用freemarker
    template-loader-path: classpath:/templates/ #设定模板的加载路径,多个以逗号分隔
    suffix: .ftl #设定模板的后缀
    content-type: text/html
    check-template-location: true #是否检查模板位置是否存在
    cache: false #是否启用模板缓存
    charset: UTF-8 #模板编码
    #一些常用配置
    allow-request-override: false #是否允许HttpServletRequest属性覆盖(隐藏)控制器生成的同名模型属性
    allow-session-override: false #是否允许HttpSession属性覆盖(隐藏)控制器生成的同名模型属性
    expose-request-attributes: false #设定所有request的属性在merge到模板的时候,是否要都添加到model中
    expose-session-attributes: false #是否在merge模板的时候,将HttpSession属性都添加到model中
    expose-spring-macro-helpers: true #设定是否以springMacroRequestContext的形式暴露RequestContext给Spring’s macro library使用
    prefer-file-system-access: true #是否优先从文件系统加载template,以支持热加载,默认为true

然后resoucres目录下新建templates目录,分别新建了hello.ftl和mv.ftl文件。

<h3>hello freemarker</h3>
<!DOCTYPE html>
<html lang="en">
    <h3>mv freemarker</h3>
    <span>I'm ${name} from mv method</span>
</html>

这里主要讲解如何集成FreeMarker,不对FreeMarker语法做过多的讲解,所以仅仅提供了两个简单的html文件作为演示。

接着再创建Controller类路由页面,该类十分简单,跳转hello页面,以及携带name=imyang跳转mv页面。

@Controller
@RequestMapping("index")
public class IndexApi {

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

    @RequestMapping("/mv")
    public ModelAndView mv(){
        ModelAndView mv = new ModelAndView("mv");
        mv.addObject("name","yanger");
        return mv;
    }

}

启动项目,分别访问http://localhost:10900/index/hello和http://localhost:10900/index/mv,可以看到已经可以展示页面信息了。

r6RfAny.png!web

源码地址: https://github.com/imyanger/springboot-project/tree/master/p19-springboot-freemarker


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK