springboot2.1入门系列十一 springboot配置freemarker

本文为Spring Boot2.1系列的第十一篇,代码可以从github下载 https://github.com/yinww/demo-springboot2.git

freemarker是1999年就发布了第一版的老牌的模板引擎,具有很多优点,也被springboot支持,freemarker的相关内容大家可以参考其他资料。

本文对freemarker的模板资源和静态资源做外部化配置进行介绍。

一、创建工程demo011

pom.xml的内容为

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yinww</groupId>
        <artifactId>demo-springboot2</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>demo011</artifactId>
    
    <dependencies>
        <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>
    </dependencies>
</project>

二、Java类

主类

package com.yinww.demo.springboot2.demo011;

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

@SpringBootApplication
public class Demo011Application {

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

}

控制类

package com.yinww.demo.springboot2.demo011.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TestController {

    @RequestMapping(value={"", "/", "index.html"})
    public ModelAndView index() {
        ModelAndView model = new ModelAndView();
        model.addObject("hi", "欢迎学习springboot 和 freemarker");
        model.setViewName("index");
        return model;
    }

}

三、配置

application.properties 添加配置

spring.freemarker.cache=false
spring.freemarker.suffix=.html
spring.freemarker.templateLoaderPath=file:E:/tmp/templates/
spring.resources.static-locations=file:E:/tmp/static/

四、html和css

E:/tmp/templates/ 路径下 index.html文件内容:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="welcome.css">
<title>hello</title>
</head>
<body>

    <div class="welcome">${hi}</div>

</body>
</html>

E:/tmp/static/ 路径下welcom.css 文件内容:

.welcome{color: #F00}

五、运行程序

启动程序后,访问 http://localhost:8080/  页面显示如下

至此实现了对freemarker的模板和静态资源的外部化配置,freemarker的其他参数配置相对比较简单,这里不做介绍。

本文内容到此结束,更多内容可关注公众号:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值