Spring Boot实战:模板引擎

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

  1、集成Thymeleaf前端

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

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

  第二步:配置thymeleaf:web

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

  prefix:指定模板所在的目录spring

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

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

  encoding&content-type:这个你们应该比较熟悉了,与Servlet中设置输出对应属性效果一致。 前端工程化

  mode:这个仍是参考官网的说明吧,而且这个是2.X与3.0不一样,本文自动引入的包是2.15。api

   第三步 编写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会自动将返回结果转为字符串。

   第五步 查看结果

 

2、Spring boot与Freemarker的集成

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

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

  二、配置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-

  三、编写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>

  四、编写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";
    }
}

  五、访问页面:

 3、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";
    }

第六步 访问结果页面:

4、总结

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

 

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

相关文章
相关标签/搜索