虽然现在很多开发,都采用了前后端完全分离的模式,即后端只提供数据接口,前端通过AJAX请求获取数据,完全不需要用的模板引擎。这种方式的优点在于前后端完全分离,并且随着近几年前端工程化工具和MVC框架的完善,使得这种模式的维护成本相对来说也更加低一点。但是这种模式不利于SEO,并且在性能上也会稍微差一点,还有一些场景,使用模板引擎会更方便,比如说邮件模板。这篇文章主要讨论Spring boot与模板引擎Thymeleaf、Freemaker以及JSP的集成。

  一、集成Thymeleaf

  第一步:引入jar包(thymeleaf对应的starter):

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

  第二步:配置thymeleaf:

spring:
thymeleaf:
prefix: classpath:/templates/
check-template-location: true
cache: false
suffix: .html
encoding: UTF-8
content-type: text/html
mode: HTML5

  prefix:指定模板所在的目录

  check-tempate-location: 检查模板路径是否存在

  cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。

  encoding&content-type:这个大家应该比较熟悉了,与Servlet中设置输出对应属性效果一致。 

  mode:这个还是参考官网的说明吧,并且这个是2.X与3.0不同,本文自动引入的包是2.15。

  第三步 编写thymeleaf模板文件:

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
</head>
<body>
<h6>Thymeleaf 模板引擎</h6>
<table border="1" bgcolor="#f0ffff">
<thead>
<tr>
<th>序号</th>
<th>标题</th>
<th>摘要</th>
<th>创建时间</th>
</tr>
</thead>
<tbody th:each="article : ${list}">
<tr>
<td th:text="${article.id}"></td>
<td th:text="${article.title}"></td>
<td th:text="${article.summary}"></td>
<td th:text="${article.createTime}"></td>
</tr>
</tbody>
</table>
</body>
</html>

  大家可以看到,thymeleaf还是比较简单的,并且最大的特点就是的标签是作为HTML元素的属性存在的,也就是说,该页面是可以直接通过浏览器来预览的,只是没有数据而已,这个很方便大家进行调试。

  第四步 配置Controller:

@Controller
@RequestMapping("/article")
public class ArticleController { @Autowired
private ArticleService articleService; @RequestMapping("/articleList.html")
public String getArticleList(Model model, String title, @RequestParam(defaultValue = "10") Integer pageSize,
@RequestParam(defaultValue = "1") Integer pageNum) {
int offset = (pageNum - 1) * pageSize;
List<Article> list = articleService.getArticles(title, 1L, offset, pageSize);
model.addAttribute("list", list);
return "article/articleList";
}
}

  注意,这里用的注解是@Controller,而不是@RestController,因为@RestController会自动将返回结果转为字符串。

  第五步 查看结果

二、Spring boot与Freemarker的集成

  1、引入jar包(Freemarker对应的starter)

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

  2、配置freemarker:

spring:
freemarker:
template-loader-path: classpath:/templates/
suffix: .ftl
content-type: text/html
charset: UTF-8
settings:
number_format: '0.##'

  除了settings外,其他的配置选项和thymeleaf类似。settings会对freemarker的某些行为产生影响,如日期格式化,数字格式化等,感兴趣的同学可以参考官网提供的说明:https://freemarker.apache.org/docs/api/freemarker/template/Configuration.html#setSetting-java.lang.String-java.lang.String-

  3、编写freemarker模板文件:

<html>
<title>文章列表</title>
<body>
<h6>Freemarker 模板引擎</h6>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>标题</th>
<th>摘要</th>
<th>创建时间</th>
</tr>
</thead>
<#list list as article>
<tr>
<td>${article.id}</td>
<td>${article.title}</td>
<td>${article.summary}</td>
<td>${article.createTime?string('yyyy-MM-dd hh:mm:ss')}</td>
</tr>
</#list>
</table> </body>
</html>

  4、编写Controller:

@Controller
@RequestMapping("/article")
public class ArticleController { @Autowired
private ArticleService articleService; @RequestMapping("/list.html")
public String getArticles(Model model, String title, @RequestParam(defaultValue = "10") Integer pageSize, Integer pageNum) {
if (pageSize == null) {
pageSize = 10;
}
if (pageNum == null) {
pageNum = 1;
}
int offset = (pageNum - 1) * pageSize;
List<Article> list = articleService.getArticles(title, 1L, offset, pageSize);
model.addAttribute("list", list);
return "article/list";
}
}

  5、访问页面:

 三、Sring boot与JSP集成:

  在正式的项目开发中,现在已经极少用jsp模板了,所以Spring boot对jsp的支持也不是很好,因此配置起来比thymeleaf和Freemaker相对来说就更复杂一点。  

第一步 引入jar包:

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>

  第一个jstl的依赖用于支持el表达式,第二个依赖用于支持jsp。注意,如果是在外部的tomcat中运行,需要将scope设置为provide,防止jar包冲突。

第二步 手动创建webapp目录:

  需要手动在main目录下创建一个webapp的目录,结构如下:

第三步 jsp路劲配置:

  在application.yml中添加如下配置:

spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp

  了解Spring mvc的应该很熟悉上面的配置。

第四步 编写jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<table border="1">
<c:forEach var="article" items="${list}">
<tr>
<td>${article.id}</td>
<td>${article.title}</td>
<td>${article.summary}</td>
<td>${article.createTime}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

第五步 编写Controller:

 @RequestMapping("/listJsp")
public String getArticleListJsp(Model model, String title, @RequestParam(defaultValue = "10") Integer pageSize, Integer pageNum) {
if (pageSize == null) {
pageSize = 10;
}
if (pageNum == null) {
pageNum = 1;
}
int offset = (pageNum - 1) * pageSize;
List<Article> list = articleService.getArticles(title, 1L, offset, pageSize);
model.addAttribute("list", list);
return "articles";
}

第六步 访问结果页面:

四、总结

  总体来讲,Spring boot对thymeleaf和Freemaker支持比较友好,配置相对也简单一点,在实际的开发中,大多也以这两种模板引擎为主,很少有用jsp的,jsp现在可能更多是在实验或者学习阶段使用。jsp配置比较麻烦一点的事情是不像前两者,网上的说法基本一致,但是对Jsp的配置有很多种说法,比如说是不是需要将jar包改成war包?jsp的依赖是否需要设置为provide等等,这个主要依赖于你是否最后要将程序部署到外部的tomcat还是直接运行jar?因为本文都是直接在idea下直接运行Application类,所以这些操作就不需要了。

我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan

Spring Boot实战:模板引擎的更多相关文章

  1. spring boot: freemarket模板引擎

    spring boot: freemarket模板引擎 freemarket模板引擎,可以和thymeleaf模板引擎共存 pom.xml引入 <!-- Freemarket --> &l ...

  2. spring boot: thymeleaf模板引擎使用

    spring boot: thymeleaf模板引擎使用 在pom.xml加入thymeleaf模板依赖 <!-- 添加thymeleaf的依赖 --> <dependency> ...

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

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

  4. SpringBoot系列:Spring Boot使用模板引擎Thymeleaf

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

  5. SpringBoot系列:Spring Boot使用模板引擎JSP

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

  6. Spring Boot Thymeleaf 模板引擎的使用

    Spring Boot 中可以支持很多模板引擎,Thymeleaf 是 Spring Boot 官方推荐使用的模板引擎,虽然在社区 Thymeleaf 的性能被许多人所吐糟,但这仍然不影响大量的开发人 ...

  7. Spring Boot整合模板引擎thymeleaf

    项目结构 引入依赖pom.xml <!-- 引入 thymeleaf 模板依赖 --> <dependency> <groupId>org.springframew ...

  8. Spring Boot整合模板引擎freemarker

    jsp本质是servlet,渲染都在服务器,freemarker模板引擎也是在服务器端渲染. 项目结构 引入依赖pom.xml <!-- 引入 freemarker 模板依赖 --> &l ...

  9. Spring Boot整合模板引擎jsp

    jsp也算是一种模板引擎吧.整合jsp前,先说一下运行SpringBoot项目的几种方式 1. 运行SpringBoot项目的几种方式 1.1 使用内嵌Tomcat运行项目 在IDE中右键运行启动类, ...

随机推荐

  1. FreeMarker生成word的代码

     用于生成word用的freemarker工具类 package com.ucap.netcheck.utils; import java.io.File; import java.io.File ...

  2. Java中四大代码块的执行顺序(附code)

    验证证的方法是写code,如下: public class test { static class A { public static String name = "hello"; ...

  3. Google的两种广告推广方式

    1搜索关键字广告推送:AdWords: 覆盖广泛:在全球最大的搜索和网络平台上进行推广. 定位精准:锁定目标客户群体,让潜在客户轻松找上门. 成本可控:仅当用户点击广告时,您才支付费用. 2.网站内容 ...

  4. git的撤销动作

    有时候我们提交完了才发现漏掉了几个文件没有加,或者提交信息写错了.想要撤消刚才的提交操作,可以使用--amend 选项重新提交: $ git commit --amend -m"修改 提交 ...

  5. python发送post请求

    urllib2.urlopen() urlib2是使用各种协议完成打开url的一个扩展包.最简单的使用方式是调用urlopen方法,比如 def urlopen(url, data=None, tim ...

  6. JAVA之旅(五)——this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块

    JAVA之旅(五)--this,static,关键字,main函数,封装工具类,生成javadoc说明书,静态代码块 周末收获颇多,继续学习 一.this关键字 用于区分局部变量和成员变量同名的情况 ...

  7. 深入理解Android IPC机制之Binder机制

    Binder是Android系统进程间通信(IPC)方式之一.Linux已经拥有的进程间通信IPC手段包括(Internet Process Connection): 管道(Pipe).信号(Sign ...

  8. cuda中模板的使用

    模板是C++的一个重要特征,它可以让我们简化代码,同时使代码更整洁.CUDA中也支持模板,这给我们编写cuda程序带来了方便.不过cuda4.0之前和之后使用模板的方法不一样,这给我们带来了少许困难. ...

  9. mysql进阶(十七)Cannot Connect to Database Server

    Cannot Connect to Database Server 缘由 由于不同的项目中使用的数据库用户名与密码出现了不一致的情况,在其中之前较早一个项目执行过程中出现"The user  ...

  10. saiku运行时报错max_length_for_sort_data 需要set higher

     infiniDB或者mysql数据库,运行时,按某个字段排序会出错.报错:max_length_for_sort_data  ... set higher. saiku报错, 也是这样. 这是数 ...