[I am learning technology in Lagou training camp] springboot integrates thymeleaf

introduction

Source of article content output: Lagou Education Java High Salary Training Camp;

Springboot integration of thymeleaf is not very practical, because now many companies are separated projects from front and back ends, interacting through interfaces. But our back-end personnel don't know much about the front-end, but want to do something to see the effect. So you can integrate thymeleaf, master some basic grammar, and you can operate well.

use

First introduce the dependency so that we can use it in the project.

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

To use in the html file, you need to import

<html lang="en" xmlns:th="http://www.thymeleaf.org">

You can use it next.

Before using, let's take a look at these basic grammars.

label

Standard expression

Variable expression: ${…}

Mainly get the parameter variables of the context

<p th:text="${title}">默认值</p>

At the same time, Thymeleaf provides built-in objects

 # ctx:上下文对象
 # vars:上下文变量
 # locale:上下文区域设置
 # request:HttpServletRequest 对象
 # response:HttpServletResponse对象
 # session:HttpSession对象
 # servletContext:ServletContext 对象

eg:

The locale country is: <span th:text="${#locale.country}">US</span>.

Select variable expression: *{…}

Generally get the attribute value from the selected object

<div th:object="${book}">
 <p>titile: <span th:text="*{title}">ຽ᷌</span>.</p>
</div>

Message expression#{…}

Message expressions are mainly used to dynamically replace and display the international content of Thymeleaf template pages.

Link expression @{…}

Generally used for page jump or resource introduction.

<a th:href="@{http://localhost:8080/order/details(orderId=${o.id})}">view</a> <a th:href="@{/order/details(orderId=${o.id})}">view</a>

strictly follow:

@{Path(parameter name=parameter value, parameter name=parameter value...)}

Fragment expression~{…}

Used to mark a fragment template and move or pass to other templates as needed

<div th:insert="~{thymeleafDemo::title}"></div>

Here is a login.html page that integrates thymeleaf

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1,shrink-to-fit=no">
    <title>用户登录界面</title>
    <link th:href="@{/login/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/login/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<!--  用户登录form表单 -->
<form class="form-signin">
    <img class="mb-4" th:src="@{/login/img/login.jpg}" width="72" height="72">
    <h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">请登录</h1>
    <input type="text" class="form-control"
           th:placeholder="#{login.username}" required="" autofocus="">
    <input type="password" class="form-control"
           th:placeholder="#{login.password}" required="">
    <div class="checkbox mb-3">
        <label>
            <input type="checkbox" value="remember-me"> [[#{login.rememberme}]]
        </label>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.button}">登录</button>
    <p class="mt-5 mb-3 text-muted">© <span th:text="${currentYear}">2019</span>-<span th:text="${currentYear}+1">2020</span></p>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='zh_CN')}">中文</a>
    <a class="btn btn-sm" th:href="@{/toLoginPage(l='en_US')}">English</a>

</form>
</body>
</html>

The final display effect is as follows:

Build a personal blog interface

Now let's build a demo, integrate mybatis, display the article list on the interface, and realize the integration of pageHelper to realize the paging effect. Display the previous page and the next page on the interface.

1. Create a table. sql is as follows:

create DATABASE blog_system
DROP TABLE IF EXISTS t_article;
CREATE TABLE t_article (
  id int(11) NOT NULL AUTO_INCREMENT,
  title varchar(50) NOT NULL COMMENT '文章标题',
  content longtext COMMENT '文章具体内容',
  created date NOT NULL COMMENT '发表时间',
  modified date DEFAULT NULL COMMENT '修改时间',
  categories varchar(200) DEFAULT '默认分类' COMMENT '文章分类',
  tags varchar(200) DEFAULT NULL COMMENT '文章标签',
  allow_comment tinyint(1) NOT NULL DEFAULT '1' COMMENT '是否允许评论',
  thumbnail varchar(200) DEFAULT NULL COMMENT '文章缩略图',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_article
-- ----------------------------
INSERT INTO t_article VALUES ('1', '2019新版Java学习路线图','Java学习路线图具体内容具体内容具体内容具体内容具体内容具体内容具体内容','2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);
INSERT INTO t_article VALUES ('2', '2019新版Python学习线路图','据悉,Python已经入驻小学生教材,未来不学Python不仅知识会脱节,可能与小朋友都没有了共同话题~~所以,从今天起不要再找借口,不要再说想学Python却没有资源,赶快行动起来,Python等你来探索' ,'2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);
INSERT INTO t_article VALUES ('3', 'JDK 8——Lambda表达式介绍',' Lambda表达式是JDK 8中一个重要的新特性,它使用一个清晰简洁的表达式来表达一个接口,同时Lambda表达式也简化了对集合以及数组数据的遍历、过滤和提取等操作。下面,本篇文章就对Lambda表达式进行简要介绍,并进行演示说明' ,'2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);
INSERT INTO t_article VALUES ('4', '函数式接口','虽然Lambda表达式可以实现匿名内部类的功能,但在使用时却有一个局限,即接口中有且只有一个抽象方法时才能使用Lamdba表达式代替匿名内部类。这是因为Lamdba表达式是基于函数式接口实现的,所谓函数式接口是指有且仅有一个抽象方法的接口,Lambda表达式就是Java中函数式编程的体现,只有确保接口中有且仅有一个抽象方法,Lambda表达式才能顺利地推导出所实现的这个接口中的方法' ,'2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);
INSERT INTO t_article VALUES ('5', '虚拟化容器技术——Docker运行机制介绍','Docker是一个开源的应用容器引擎,它基于go语言开发,并遵从Apache2.0开源协议。使用Docker可以让开发者封装他们的应用以及依赖包到一个可移植的容器中,然后发布到任意的Linux机器上,也可以实现虚拟化。Docker容器完全使用沙箱机制,相互之间不会有任何接口,这保证了容器之间的安全性' ,'2019-10-10', null, '默认分类', '‘2019,Java,学习路线图', '1', null);

2. Create a springboot project and introduce dependencies as follows:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.1.3</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!--分页助手-->
<!--导入pagehelper相关依赖-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>

3. Create an entity class.

public class Article {

    private Integer id;
    private String title;
    private String content;
    private Date created;
    private Date modified;
    private String categories;
    private String tags;
    private Integer allowComment;
    private String thumbnail;
    getter()/setter()
}

5. Create a mapper interface

@Mapper
public interface ArticleMapper {

    List<Article> selectList();
}

6. Create the xml file corresponding to the mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.quellanan.springboothomework.mapper.ArticleMapper">

    <select id="selectList" resultType="article">
        select * from tb_article
    </select>
</mapper>

7. Create service and implementation class. Use PageHelper to implement paging

public interface ArticleService {
    List<Article> selectList(int index,int size);
}


@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;


    @Override
    public List<Article> selectList(int index,int size) {
        PageHelper.startPage(index,size);
        List<Article> articles = articleMapper.selectList();
        return articles;
    }
}

8. Create a controller layer interface

@Controller
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping("/")
    public String list(Model model, @RequestParam(required = false)Integer index, @RequestParam(required = false)Integer size){
        if(index==null ||size==null){
            index=1;
            size=2;
        }
        List<Article> articles = articleService.selectList(index,size);
        PageInfo<Article> pageInfo=new PageInfo<>(articles);
        model.addAttribute("articles", articles);
        model.addAttribute("pageInfo", pageInfo);
        return "client/index";
    }
}

9. Add configuration in the configuration file.

# Mysql数据库连接配置 : com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

#开启驼峰命名匹配映射mapper
mybatis.configuration.map-underscore-to-camel-case=true

#配置mybatis的xml映射配置文件路径
mybatis.mapper-locations=classpath:mapper/*.xml
#配置mybatis映射配置文件中实体类别名
mybatis.type-aliases-package=cn.quellanan.springboothomework.pojo


# thymeleaf页面缓存设置
spring.thymeleaf.cache=false

# 配置pagehelper参数
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

10. Introduce static file resources.

11. Edit the index.html file.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 载入文章头部页面,位置在/client文件夹下的header模板页面,模板名称th:fragment为header -->
<div th:replace="/client/header::header(null,null)" />
<body>
<div class="am-g am-g-fixed blog-fixed index-page">
    <div class="am-u-md-8 am-u-sm-12">


        <!-- 文章遍历并分页展示 : 需要同学们手动完成,基本样式已经给出,请使用th标签及表达式完成页面展示 -->
        <div th:each="article,stat:${articles}" th:value="article">
            <article class="am-g blog-entry-article">

                <div class="am-u-lg-6 am-u-md-12 am-u-sm-12 blog-entry-text">
                    <!-- 文章分类 -->
                    <span class="blog-color"style="font-size: 15px;"><a>默认分类</a></span>
                    <span>&nbsp;&nbsp;&nbsp;</span>
                    <!-- 发布时间 -->
                    <span style="font-size: 15px;" th:text="'发布于 '+ ${article.created}" />
                    <h2>
                        <!-- 文章标题 -->
                        <div><a style="color: #0f9ae0;font-size: 20px;" th:text="${article.title}" />
                        </div>
                    </h2>
                    <!-- 文章内容-->
                    <div style="font-size: 16px;" th:text="${article.content}" />
                </div>
            </article>
        </div>
        <div>
            <a class="btn btn-sm" th:href="@{/(index=1,size=2)}">首页</a>

            <a class="btn btn-sm" th:href="@{/(index=${pageInfo.getPageNum()-1},size=2)}">上一页</a>
            <a class="btn btn-sm" th:href="@{/(index=${pageInfo.getPageNum()}+1,size=2)}">下一页</a>
            <a class="btn btn-sm" th:href="@{/(index=${pageInfo.getPages()},size=2)}">尾页</a>
        </div>




    </div>
    <!-- 博主信息描述 -->
    <div class="am-u-md-4 am-u-sm-12 blog-sidebar">
        <div class="blog-sidebar-widget blog-bor">
            <h2 class="blog-text-center blog-title"><span>子慕</span></h2>
            <img th:src="@{/assets/img/me.jpg}" alt="about me" class="blog-entry-img"/>
            <p>
                Java后台开发
            </p>
            <p>个人博客小站,主要发表关于Java、Spring、Docker等相关文章</p>
        </div>
        <div class="blog-sidebar-widget blog-bor">
            <h2 class="blog-text-center blog-title"><span>联系我</span></h2>
            <p>
                <a><span class="am-icon-github am-icon-fw blog-icon"></span></a>
                <a><span class="am-icon-weibo am-icon-fw blog-icon"></span></a>
            </p>
        </div>
    </div>

</div>
</body>
<!-- 载入文章尾部页面,位置在/client文件夹下的footer模板页面,模板名称th:fragment为footer -->
<div th:replace="/client/footer::footer" />
</html>

12. Test

Start project, visit

http://localhost:8080/

to sum up

If it is simple to use, it is very convenient to integrate thymeleaf, but now mainstream projects should be separated from the front and back ends. However, small partners who are full stacks can still understand. We know that this technology is enough. When we want to use it Just get started

Guess you like

Origin blog.csdn.net/qq_27790011/article/details/107017827