SpringBoot模板引擎

SpringBoot模板引擎


一、什么是模板引擎?

模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。
SpringBoot 推荐使用模板引擎来渲染html,如果你不是历史遗留项目,一定不要使用JSP,常用的模板引擎很多,有freemark,thymeleaf等,其实都大同小异其中springboot 强烈推荐的是用thymeleaf

二、使用步骤

1.导入依赖

pom.xml文件中添加thymeleaf的支持,并且删除JSP的支持

<!--&lt;!&ndash;JavaServer Pages Standard Tag Library,JSP标准标签库&ndash;&gt;-->
<!--<dependency>-->
    <!--<groupId>javax.servlet</groupId>-->
    <!--<artifactId>jstl</artifactId>-->
<!--</dependency>-->
<!--&lt;!&ndash;内置tocat对Jsp支持的依赖,用于编译Jsp&ndash;&gt;-->
<!--<dependency>-->
    <!--<groupId>org.apache.tomcat.embed</groupId>-->
    <!--<artifactId>tomcat-embed-jasper</artifactId>-->
<!--</dependency>-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2.删除(注释掉)application.properties文件里面视图解析器内容

#spring.mvc.view.prefix=/WEB-INF/jsp/
#spring.mvc.view.suffix=.jsp

3新建Controller

package cn.oy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/tpl")
public class ThymeleafController {
    @RequestMapping("/testThymeleaf")
    public String testThymeleaf(ModelMap map){
        // 设置属性
        map.addAttribute("name", "enjoy");
        // testThymeleaf:为模板文件的名称
        // 对应src/main/resources/templates/testThymeleaf.html
        return "testThymeleaf";
    }

}

4.新建一个html文件,输出上面controller的结果

在resources目录里面新建一个templates目录,在目录里面新建testThymeleaf.html文件(springboot约定大约配置,Springboot默认的模板配置路径为:src/main/resources/templates)

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>enjoy</title>
</head>
<body>
<h1 th:text="${name}"/>
</body>
</html>

在浏览器上输入:localhost:8080/tpl/testThymeleaf,可以看到页面。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值