前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >(二)SpringBoot2.0基础篇- 静态资源的访问及Thymeleaf模板引擎的使用

(二)SpringBoot2.0基础篇- 静态资源的访问及Thymeleaf模板引擎的使用

作者头像
发布2019-02-21 10:13:19
1.4K0
发布2019-02-21 10:13:19
举报
文章被收录于专栏:F_AlexF_AlexF_Alex

一、描述

在应用系统开发的过程中,不可避免的需要使用静态资源(浏览器看的懂,他可以有变量,例:HTML页面,css样式文件,文本,属性文件,图片等);

并且SpringBoot内置了Thymeleaf模板引擎,可以使用模板引擎进行渲染处理,默认版本为2.1,可以重新定义Thymeleaf的版本号,在maven的配置文件中配置如下内容:

<properties>
    <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>

二、默认静态资源的映射

Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则:

  • /static
  • /public
  • /resources

/META-INF/resources

SpringBoot默认会从META-INF/resources下的static、public、resources三个目录下查找对应的静态资源,而模板引擎的模板默认需要放在resources的templates目录下;

三、示例

1、静态资源的访问

  • 创建maven项目,在resources目录下创建static、templates文件夹,将图片success.jpg放置在static中;
  • 创建启动类,详情请看:(一)SpringBoot基础篇- 介绍及HelloWorld初体验
  • 启动项目,访问,http://localhost:8080/success.jpg,图片即可在页面展示成功;

2、Thymeleaf模板引擎

  ①、使用Thymeleaf前,需引入依赖类库:

<!-- 使用thymeleaf模板-->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

  ②、创建启动类Application.java;

  ③、创建控制层HelloController.java;

package com.cn.controller;/**
 * @Description: Created by xpl on 2018-05-01 13:23.
 */

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;

/**
 * Created by xpl on 2018-05-01 13:23
 **/

@RestController
public class HelloController {

    @RequestMapping("/getThymeleaf")
    public ModelAndView getThymeleaf() {
        ModelAndView modelAndView = new ModelAndView("hello");
        modelAndView.addAllObjects(new HashMap<String, String>(){
            {
                this.put("name","Andy");
            }
        });
        return modelAndView;
    }

}

  ④、创建Thymeleaf模板hello.html,访问变量使用th:进行访问;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>
        Title</title>
</head>
<body>

<h1>Hello,</h1>
<h1 th:text="${name}"/>
</body>
</html>

  ⑤、启动项目,并访问http://localhost:8080/getThymeleaf,如下:

  目录结构如下:

完整示例:https://gitee.com/lfalex/spring-boot-example

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-05-01 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、描述
  • 二、默认静态资源的映射
  • 三、示例
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档