Personal blog site record 2

Article Directory

1. Judgement of th condition:

Reference from:



gt:great than(大于)>
ge:great equal(大于等于)>=
lt:less than(小于)<
le:less equal(小于等于)<=
ne:not equal(不等于)!=

when using it:

<div class="article" th:if=" ${articleSize} ge '2'">

Indicates that this will be displayed when the backend articleSizeis greater than or equal to .2div

(2) The use of th:each:

To traverse the elements in the attribute:

<tr th:each="article: ${articleList}">
    <td th:text="${article.articleName}"></td>
    <td th:text="${article.createdName}"></td>

From 1to 10:


To replace the 10 inside with a parameter, you might look like this:


But writing this way will report an error.

To use it correctly, it should be like this:

(3) The use of th:switch:


<div th:switch="${currentPage}">
    <h1 case="1">1</h1>
    <h1 case="2">2</h1>
    <h1 case="*">3</h1>

*Indicates defaultthat if the above conditions are not met, it will be executed default. For example, when currentPageis 1the time to see only the first label.

(4) Combined use of th:switch and th:each:

The example written below:

<li class="li3 floatLeft wid35" 
     <div class="indexSelected" th:case = "${i}">
          <h1 class="fontNor textAlCenter font10 rgbTextWhite" th:text="${i}"></h1>
     <div class="indexNotSelected" th:case="*" onmouseover="'red';"
          <h1 class="fontNor textAlCenter font10" th:text="${i}"></h1>
2. Mybatis use:


In pom.xmladd dependencies:


Then reload the mavenongoing mybatisinstallation.

ymlTo configure the data source as mysqland jdbcwhen the same on the line:

    name: localhost
    url: jdbc:mysql://localhost:3306/mydatabase #url
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver

Create a software package pojoand create a articleclass in it to return the object of the query result:

package com.example.myblogweb.pojo;
public class article {
    private int articleId;
    private String articleName;
    private String createdDate;
    private String createdTime;
    private int readNm;
    private int up;
    private int comment;
    public int getReadNm() {
        return readNm;
    public int getArticleId() {
        return articleId;
    public int getUp() {
        return up;
    public int getComment(){
        return comment;
    public String getArticleNm() {
        return articleName;
    public String getCreatedDate(){
        return createdDate;
    public String getCreatedTime(){
        return createdTime;

Create a package Mapper, create one in it interface, articleMapperclass:

package com.example.myblogweb.mapper;

import com.example.myblogweb.pojo.article;

import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper   //表示了这是一个mybatis的mapper类
public interface articleMapper {
    List<article> articleList();
    article getArticleById(int articleId);  //使用id获取article
    int addArticle(article article);  //向数据库中添加文章
    boolean updateArticle(article article);  //对文章信息进行修改
    boolean deleteArticle(int articleId);

In the resourcesCreate the following articleMapperdirectory, in articleMappercreating a file directory, file name articleMapper.xml, add the code, according to change:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-// Mapper 3.0//EN"

<mapper namespace="com.example.myblogweb.mapper.articleMapper">
    <select id="articleList" resultType="article"    
            useCache="true">  <!--结果类型类型-->  <!-- 启用缓存 -->
            select * from articleinfo

    <select id="getArticleById" resultType="article" parameterType="int">  
        select * from  articleinfo where articleId = #{articleId}

    <insert id="addArticle" parameterType="article">   <!-- 参数类型 -->
         insert into articleinfo values(#{articleId}

    <update id="updateArticle" parameterType="article">
         update articleinfo set articleId=#{articleId}
         where articleId = #{articleId}
    <delete id="deleteArticle" parameterType="int">
         delete from articleinfo where articleId=#{articleId}

In the ymlAdd configuration:

mybatis: # mybatis配置
  # model的包
  type-aliases-package: com.example.myblogweb.pojo
    map-underscore-to-camel-case: true
  mapper-locations: classpath:articleMapper/*.xml

In controlleruse:

public class indexController {
    @Autowired    // 自动注入,spring boot会帮我们实例化一个对象
    private articleMapper articleMapper;
    @RequestMapping(value = "/a", method = RequestMethod.GET)  
    public String a(ModelMap map) {
        return "index";

Then enter: in the URL, localhost:8080/aand observe the console output:

Insert picture description here

you can see the normal output ArticleName.

(1) Rewrite jdbcthe part used before :

Use mybatisto jdbctemplaterewrite the previously written part. Finding the content of the article can all be obtained through the above getArticleById, which can be said to be a lot more convenient. The only thing that needs to be rewritten is the increase in page views.

In mappercreating a middle 浏览量+1way:

boolean addReadNm(int articleId);  //浏览量
boolean addUp(int articleId);  //点赞+1
boolean addComment(int articleId);  //评论+1

Add in the corresponding xml:

    <update id="addReadNm" parameterType="int">
        update articleinfo set articleinfo.readNm = articleinfo.readNm+1 
        where articleId=#{articleId}

    <update id="addUp" parameterType="int">
        update articleinfo set articleinfo.up = articleinfo.up+1 
        where articleId=#{articleId}

    <update id="addComment" parameterType="int">
        update articleinfo set articleinfo.comment = articleinfo.comment+1 
        where articleId=#{articleId}

In controllerthe overridden method:

    @RequestMapping(value = "/article/{articleID}", method = RequestMethod.GET)     
    public String Article(@PathVariable("articleID") Integer articleID, ModelMap map) {
        article article1 = articleMapper.getArticleById(articleID);
        if (article1 == null)
            return "404";
        else {
            map.addAttribute("articleName", article1.getArticleNm());
            map.addAttribute("createdDate", article1.getCreatedDate());
            map.addAttribute("createdTime", article1.getCreatedTime());
            map.addAttribute("readNm", article1.getReadNm());
            map.addAttribute("comment", article1.getComment());
            map.addAttribute("up", article1.getUp());
            return "article";

The code was reduced a lot at once, and the page views increased after the test and the non-existent pages were all normal.

(2) Add article:

When adding an article, first get the total number of articles, and then directly call the addArticle()method defined above . idThe article added is the number of articles just found +1.

The total number of articles can be obtained by calculating the length of the full table query result. The interface for the full table query has just been written, that is articleList(), the sizenumber of articles can be obtained through it :


Then you can call the addArticle()interface by adding an article . Before that, add a constructor to add:

    public article(int articleId
            ,String articleName
            ,String createdDate
            ,String createdTime
            ,int readNm
            ,int up
            ,int comment)
        this.articleId = articleId;
        this.articleName = articleName;
        this.createdDate = createdDate;
        this.createdTime = createdTime;
        this.readNm = readNm;
        this.up = up;
        this.comment = comment;

After everything is ready, you can add articles like this:

articleMapper.addArticle(new article(articleMapper.articleList().size()+1
                         ,"2021-6-1 11:21:56"

The method is written in controller, open the webpage, refresh the database, you can see that it has been added successfully:

Insert picture description here

because my parameters are hard to write, the two records are the same. In actual use, you need to replace these parameters with the parameters submitted by the form.

3. Paging using page-helper:

On mybatisthe basis of the following operations:


<dependency> <!-- pagehelper-->

ymlMedium placement:

  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql

In controlleradd the code test:

@RequestMapping(value = "/a", method = RequestMethod.GET)  
public String aa(ModelMap map) {
    PageHelper.startPage(1,3);  //pageNum:当前是第几页 , pageSize:每页多少条数据。 
    //这里 articleMapper.articleList()是全表查询,将所有元素都放到articles中
    List<article> articles=articleMapper.articleList();  //这一句查询必须放到这里,否则会无效
    //PageInfo会对articles进行分页,他不会对 articleList() 全表查询的结果进行修改或颠倒顺序
    PageInfo<article> pageInfo = new PageInfo<article>(articles);
    return "index";          

Log in localhost:8080/a, and the pageInfoinformation is output:

Insert picture description here

Look at the output roughly:

    pageNum=1   //当前是第一页
        , pageSize=3    //每页显示3条数据
        , size=3       //当前页有3条数据
        , startRow=1   //第1条数据开始(针对数据库)
        , endRow=3     //第3条数据结束
        , total=15     //一共15条数据
        , pages=5      //一共5页
        , list=Page{  //当前页信息
        , pageNum=1
        , pageSize=3
        , startRow=0
        , endRow=3
        , total=15
        , pages=5
        , reasonable=true
        , pageSizeZero=false
    [[email protected]       
        , [email protected]
        , [email protected]]  //这个数组中的元素是第一页的三条数据
        , prePage=0        //前一页是第0页
        , nextPage=2       //下一页是第2页
        , isFirstPage=true  //是第一页?
        , isLastPage=false  //是最后一页?
        , hasPreviousPage=false    //有前一页?
        , hasNextPage=true      //有下一页?
        , navigatePages=8       //每页末尾显示的页码个数
        , navigateFirstPage=1   //末尾的页码第一位
        , navigateLastPage=5    //末尾的页码最后一位
        , navigatepageNums=[1, 2, 3, 4, 5]      //末尾的页码

To obtain the specific information in the above information, directly find in pageInfothe getmethod:

article article1 = pageInfo.getList().get(0)

PagerHelperThere are four other methods for setting paging, you can refer to:

When you need to go to another page, for example, you can write:

@RequestMapping(value = "/a", method = RequestMethod.GET)   //路径为home ,get方式执行以下函数
    public String aa(ModelMap map) {
        PageHelper.startPage(1,5);   //第一页开始,每页显示5元素
        List<article> articles=articleMapper.articleList();
        PageInfo<article> pageInfo1 = new PageInfo<article>(articles);

        List<article> articles1=articleMapper.articleList();  //必须添加查询,否则失效
        PageInfo<article> pageInfo2 = new PageInfo<article>(articles1);
        return "index";          
Insert picture description here

Rewrite a function:

public PageInfo<article> pageInfo(int pageNm,int pageSize)
    List<article> articles=articleMapper.articleList();
    return  new PageInfo<article>(articles);

Then you pageNmcan jump to the data record of the corresponding page as long as you pass in.

(1) Front-end article dynamic display:

Each article displays five articles, so I just need to refer to the page number (for example localhost:8080/home/2, the second page), then startPagejump to the second page, and then display the information of the five articles on the second page. In addition to the above functions, you also need to define another function to map data to the front end:

    public void articleInfoSed(int articleCount,PageInfo<article> info,ModelMap map)
        for (int i=0;i<articleCount;i++) {
            map.addAttribute("articleTitle" + (i + 1), info.getList().get(i).getArticleNm());   //文章名
            map.addAttribute("articleDate" + (i+1), info.getList().get(i).getCreatedDate());   //创建日期
            map.addAttribute("articleReadNm" + (i+1), info.getList().get(i).getReadNm());   //浏览数
            map.addAttribute("articleUpNm" + (i+1), info.getList().get(i).getUp());   //点赞数
            map.addAttribute("articleCommentNm" + (i+1), info.getList().get(i).getComment());   //留言数

When using it, as long as:

 @RequestMapping(value = "/home/{pageIndex}", method = RequestMethod.GET)   //路径为home ,get方式执行以下函数
    public String HomePageIndex(@PathVariable("pageIndex") Integer pageIndex, ModelMap map) {
        //进行分页,每五篇文章分页,并跳转到第 pageIndex页
        PageInfo<article> pageInfo = pageInfo(pageIndex,5);  

        return "homePage";

Log in to localhost:8080/home/3view the information on the third page, and find that the article information has been mapped:

Insert picture description here
(2) 5What if the number of articles on the last page is insufficient :

If the last article is insufficient 5, the previous info.getList().get(i).getArticleNm()operation will report an error, so the indexvalue of the article content should be obtained according to the number of articles on the current page, which is to 5change it to pageInfo.getSize(). Secondly, we need to modify the front-end display to display as many articletags as there are articles in the last night :

@RequestMapping(value = "/home/{pageIndex}", method = RequestMethod.GET)   //路径为home ,get方式执行以下函数
    public String HomePageIndex(@PathVariable("pageIndex") Integer pageIndex, ModelMap map) {
        PageInfo<article> pageInfo = pageInfo(pageIndex,5);


        return "homePage";

The front-end receives articleSizeto determine articlethe display of tags. I divwrote the tags of the five articles one by one , so I can change them one by one :

<!-- 文章标签1不用管 -->
<!-- 文章标签2,有2篇文章以上时显示 -->
<div class="article" th:if=" ${articleSize} ge '2'"> 中间的属性已省略  </div>   
<!-- 文章标签3,有3篇文章以上时显示 -->
<div class="article" th:if=" ${articleSize} ge '3'"> 中间的属性已省略  </div>
<!-- 文章标签4,有4篇文章以上时显示 -->
<div class="article" th:if=" ${articleSize} ge '4'"> 中间的属性已省略  </div>
<!-- 文章标签5,有5篇文章时显示 -->
<div class="article" th:if=" ${articleSize} eq '5'">  中间的属性已省略  </div>

A total 16of data, open to the fourth page to see: (the function of the button below has not been done yet, don’t care)

Insert picture description here

In addition, logically speaking, when the address page I enter ( localhost:8080/home/5) is greater than my total number of pages 4, it should be Will report an error. But after many experiments, if the input is greater than the maximum number of pages, it will automatically return to the last page, which is beyond my expectation.
But you can still add processing, when the input page number is greater than the total number of pages, it will return to the 404page:

    return "404";
(3) Click the button to jump:

First modify the front-end code to create the corresponding number of buttons based on the total number of pages. When the button number is the same as the current page number, it turns red, otherwise white:

map.addAttribute("currentPage",pageIndex);   //当前页面编号

The front end uses to th:eachgenerate totalPagea button, and then the button currentPagewhose subscript is equal to the button becomes red, otherwise the button is white:

<li class="li3 floatLeft wid35" 
    <div class="indexSelected" th:case = "${i}">
        <h1 class="fontNor textAlCenter font10 rgbTextWhite" th:text="${i}"></h1>
    <div class="indexNotSelected" th:case="*" onmouseover="'red';"
        <h1 class="fontNor textAlCenter font10" th:text="${i}"></h1>

When you open the webpage, localhost:8080/home/3you can see that the button on the third page turns red:

Insert picture description here

Then there is the jump of the button. I used to use the submission form. In fact, I only need to use the link to jump to the corresponding page:

<li class="li3 floatLeft wid35 " 
    <a th:href="${i}">
        <div class="indexSelected" th:case = "${i}" >
             <h1 class="fontNor textAlCenter font10 rgbTextWhite" th:text="${i}"></h1>
        <div class="indexNotSelected" th:case="*" onmouseover="'red';"
                onmouseout="'black';" >
             <h1 class="fontNor textAlCenter font10" th:text="${i}"></h1>

In this way, the button jump is realized.

(4) Previous page and next page:
map.addAttribute("PrePage",pageInfo.getPrePage()); //上一页
map.addAttribute("NextPage",pageInfo.getNextPage()); //下一页

Previous page:

<!-- 上一页是0时按钮无效 -->
<li class="li3 floatLeft wid40" th:switch="${PrePage}">
    <a class="textDecNo" href="javascript:void(0);" th:case="0">
         <div class="noIndex">
             <h1 class="fontNor textAlCenter font10">上一页</h1>
    <a class="textDecNo" th:href="${PrePage}" th:case="*">
         <div class="indexNotSelected"
             onmouseout="'white';'black';" >
             <h1 class="fontNor textAlCenter font10">上一页</h1>

Next page:

<!-- 当前页是最后一页时,按钮无效 -->
<li class="li3 floatLeft wid40" th:switch="${currentPage}">
    <a class="textDecNo" href="javascript:void(0);" th:case="${totalPage}">
        <div class="noIndex">
            <h1 class="fontNor textAlCenter font10">下一页</h1>
    <a class="textDecNo" th:href="${NextPage}" th:case="*">
        <div class="indexNotSelected"  
        onmouseout="'white';'black';" >
            <h1 class="fontNor textAlCenter font10">下一页</h1>