Personal blog site record 2

Article Directory

1. Judgement of th condition:

Reference from: https://blog.csdn.net/qq_31424825/article/details/79052192

(1)th:if:

symbol:

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

when using it:

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

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>
</tr>

From 1to 10:

th:each="i:${#numbers.sequence(1,10)}"

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

th:each="i:${#numbers.sequence(1,${totalPage})}"

But writing this way will report an error.

To use it correctly, it should be like this:

th:each="i:${#numbers.sequence(1,totalPage)}"
(3) The use of th:switch:

judgment:

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

*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" 
    th:each="i:${#numbers.sequence(1,totalPage)}" 
    th:switch="${currentPage}">
     <div class="indexSelected" th:case = "${i}">
          <h1 class="fontNor textAlCenter font10 rgbTextWhite" th:text="${i}"></h1>
     </div>
     <div class="indexNotSelected" th:case="*" onmouseover="this.style.color='red';"
          onmouseout="this.style.color='black';">
          <h1 class="fontNor textAlCenter font10" th:text="${i}"></h1>
     </div>
</li>
2. Mybatis use:

mybatisLink: https://mybatis.org/mybatis-3/zh/index.html

In pom.xmladd dependencies:

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>

Then reload the mavenongoing mybatisinstallation.

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

spring:
  datasource:
    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类
@Repository
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 "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


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

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

    <insert id="addArticle" parameterType="article">   <!-- 参数类型 -->
         insert into articleinfo values(#{articleId}
         ,#{articleNm}
         ,#{createdDate}
         ,#{createdTime}
         ,#{readNm}
         ,#{up}
         ,#{comment})
    </insert>

    <update id="updateArticle" parameterType="article">
         update articleinfo set articleId=#{articleId}
                              ,articleName=#{articleNm}
                              ,createdDate=#{createdDate}
                              ,createdTime=#{createdTime}
                              ,readNm=#{readNm}
                              ,up=#{up}
                              ,comment=#{comment}
         where articleId = #{articleId}
    </update>
    <delete id="deleteArticle" parameterType="int">
         delete from articleinfo where articleId=#{articleId}
    </delete>
</mapper>

In the ymlAdd configuration:

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

In controlleruse:

@Controller
public class indexController {
    @Autowired    // 自动注入,spring boot会帮我们实例化一个对象
    private articleMapper articleMapper;
    
    @RequestMapping(value = "/a", method = RequestMethod.GET)  
    public String a(ModelMap map) {
        System.out.println(articleMapper.getArticleById(1).getArticleNm());
        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>

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

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

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)
        {
            map.addAttribute("errCode","404");
            map.addAttribute("errMess","文章不存在");
            return "404";
        }
        else {
            //浏览量+1
            articleMapper.addReadNm(articleID);
            //静态加载到前端
            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 :

System.out.println("文章总数"+articleMapper.articleList().size());

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
                         ,"c语言学习笔记"
                         ,"2021-6-1"
                         ,"2021-6-1 11:21:56"
                         ,0,0,0));

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:

pom.xmlConfiguration:

<dependency> <!-- pagehelper-->
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.5</version>
</dependency>

ymlMedium placement:

pagehelper:
  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不是实例对象
    PageHelper.startPage(1,3);  //pageNum:当前是第几页 , pageSize:每页多少条数据。 
    //这里 articleMapper.articleList()是全表查询,将所有元素都放到articles中
    List<article> articles=articleMapper.articleList();  //这一句查询必须放到这里,否则会无效
    //PageInfo会对articles进行分页,他不会对 articleList() 全表查询的结果进行修改或颠倒顺序
    //所以修改之前的全表查询代码按照文章创建时间进行降序排列,那么最新的文章也会被分在最前面
    PageInfo<article> pageInfo = new PageInfo<article>(articles);
    System.out.println(pageInfo);
    
    return "index";          
    }

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

Insert picture description here


Look at the output roughly:

PageInfo{
    pageNum=1   //当前是第一页
        , pageSize=3    //每页显示3条数据
        , size=3       //当前页有3条数据
        , startRow=1   //第1条数据开始(针对数据库)
        , endRow=3     //第3条数据结束
        , total=15     //一共15条数据
        , pages=5      //一共5页
        , list=Page{  //当前页信息
        count=true
        , 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:

//获取当前页面第一篇文章的文章id:
article article1 = pageInfo.getList().get(0)
System.out.println(article1.getArticleId());

PagerHelperThere are four other methods for setting paging, you can refer to: https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md

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);
        System.out.println("第一页:"+pageInfo1);

        PageHelper.startPage(pageInfo1.getNextPage(),5);
        List<article> articles1=articleMapper.articleList();  //必须添加查询,否则失效
        PageInfo<article> pageInfo2 = new PageInfo<article>(articles1);
        System.out.println("第二页:"+pageInfo2);
        
        return "index";          
    }
Insert picture description here


Rewrite a function:

public PageInfo<article> pageInfo(int pageNm,int pageSize)
{
    PageHelper.startPage(pageNm,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) {
        personalInfoSw(map);
        
        //进行分页,每五篇文章分页,并跳转到第 pageIndex页
        PageInfo<article> pageInfo = pageInfo(pageIndex,5);  
        articleInfoSed(5,pageInfo,map);

        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) {
        personalInfoSw(map);
        PageInfo<article> pageInfo = pageInfo(pageIndex,5);

        //提交当前页的文章个数给前端,前端会进行判断文章个数,从而显示几个article标签
        map.addAttribute("articleSize",pageInfo.getSize());
        articleInfoSed(pageInfo.getSize(),pageInfo,map);  
        //用pageInfo.getSize()获取当前页文章数

        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:

if(pageIndex>pageInfo.getPages())
{
    map.addAttribute("errCode","404");
    map.addAttribute("errMess","文章不存在");
    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);   //当前页面编号
map.addAttribute("totalPage",pageInfo.getPages());//总的页数

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" 
    th:each="i:${#numbers.sequence(1,totalPage)}"    
    th:switch="${currentPage}">   
    <div class="indexSelected" th:case = "${i}">
        <h1 class="fontNor textAlCenter font10 rgbTextWhite" th:text="${i}"></h1>
    </div>
    <div class="indexNotSelected" th:case="*" onmouseover="this.style.color='red';"
         onmouseout="this.style.color='black';">
        <h1 class="fontNor textAlCenter font10" th:text="${i}"></h1>
    </div>
</li>

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 " 
th:each="i:${#numbers.sequence(1,totalPage)}" 
th:switch="${currentPage}">
    <a th:href="${i}">
        <div class="indexSelected" th:case = "${i}" >
             <h1 class="fontNor textAlCenter font10 rgbTextWhite" th:text="${i}"></h1>
        </div>
        <div class="indexNotSelected" th:case="*" onmouseover="this.style.color='red';"
                onmouseout="this.style.color='black';" >
             <h1 class="fontNor textAlCenter font10" th:text="${i}"></h1>
        </div>
    </a>
</li>

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>
         </div>
    </a>
    <a class="textDecNo" th:href="${PrePage}" th:case="*">
         <div class="indexNotSelected"
             onmouseover="this.style.backgroundColor='red';this.style.color='white';"
             onmouseout="this.style.backgroundColor='white';this.style.color='black';" >
             <h1 class="fontNor textAlCenter font10">上一页</h1>
         </div>
    </a>
</li>

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>
        </div>
    </a>
    <a class="textDecNo" th:href="${NextPage}" th:case="*">
        <div class="indexNotSelected"  
        onmouseover="this.style.backgroundColor='red';this.style.color='white';"
        onmouseout="this.style.backgroundColor='white';this.style.color='black';" >
            <h1 class="fontNor textAlCenter font10">下一页</h1>
        </div>
    </a>
</li>