SpringBoot博客开发日常记录-搜索功能以及搜索词汇云图显示

博客中需要包含一个简单的检索功能,我自己设定的目标是能够通过检索一定的关键词来获取带有这些关键词的标题的博客列表,并且能够通过云图展示搜索趋势。

1. Service

在ArticleService.java中添加三个方法

//模糊查找 title的相关内容
List<Article> getArticleListByTitle(String contents);
//搜索记录相关
List<Search> getSearchHistory();
int addSearchHistory(Search search);

在ArticleServiceImpl.java中对其进行实现

	@Override
     /**
       * @description: 查找的匹配方式是%contents%,如果检索到,则会将这个contents加到search History中
       * @param [contents]
       * @return java.util.List
       * @throws
       * @author Alden He
       * @date 2019/5/23 19:04
       */
    public List<Article> getArticleListByTitle(String contents){
        List<Article> list=articleMapper.getArticleListByTitle("%"+contents+"%");
        if(list!=null&&list.size()>0)articleMapper.addSearchHistory(new Search(contents,1));
        return list;
    }
    //搜索记录相关
    @Override
    public List<Search> getSearchHistory(){
        return articleMapper.getSearchHistory();
    }
    @Override
    public int addSearchHistory(Search search){
        return articleMapper.addSearchHistory(search);
    }

这里的一个处理逻辑是如果搜索结果存在则将搜索词添加到搜索历史中

2. Mapper

在ArticleMapper添加如下方法

	List<Article> getArticleListByTitle(String contents);
	//搜索记录相关
    List<Search> getSearchHistory();
    int addSearchHistory(Search search);

在ArticleMapper.xml中的实现为

	<select id="getArticleListByTitle" parameterType="java.lang.String" resultMap="articleResultMapList">
        select article.id,article.title,article.shortcut,
               DATE_FORMAT(article.publishDate,'%Y-%m-%d') publishDate,
               DATE_FORMAT(article.updateDate,'%Y-%m-%d') updateDate,article.likes,article.visitTimes,article.isStick,article.cover,
               user.id as user_id,user.username
        from article left join user on article.authorId=user.id where article.title like #{contents}
        order by isStick desc,article.id desc
    select>
    <select id="getSearchHistory" resultType="com.nevergetme.nevergetmeweb.bean.Search">
        select * from SearchHistory
    select>
    <insert id="addSearchHistory" parameterType="com.nevergetme.nevergetmeweb.bean.Search" keyProperty="id" useGeneratedKeys="true">
        insert into SearchHistory(content,times) values(#{content},#{times}) on duplicate key update times=times+1
    insert>

3. SQL建表

需要建立存储搜索记录的表

CREATE TABLE `searchhistory` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `content` varchar(200) NOT NULL,
  `times` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `content` (`content`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

4. controller层

controller层比较简单,首先是返回search模板

	@GetMapping("/search")
    public String getSearchPage(){
        return "search";
    }

然后是具体的处理请求的controller

    @RequestMapping(value = "/article/searchArticle",method = RequestMethod.POST)
    public @ResponseBody List<Article> searchArticle(@RequestParam("contents")String contents){
        return articleService.getArticleListByTitle(contents);
    }

    @RequestMapping("/article/getSearchHistory")
    public @ResponseBody List<Search> getSearchHistory(){
        return articleService.getSearchHistory();
    }

5. HTML

编写界面时需要引入几个库

  1. 词云图
  2. 数据展示:echarts

具体代码如下


<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>NeverGetMetitle>
    <link rel="shortcut" th:href="@{/icon/java.svg}"/>
    <script th:src="@{/js/jquery.min.js}">script>
    <script th:src="@{/js/bootstrap.min.js}">script>
    <script th:src="@{/js/popper.min.js}">script>
    <link th:href="@{/css/bootstrap.css}" rel="stylesheet">
    
    <script th:src="@{/js/popper.min.js}">script>
    <script th:src="@{plug/echarts/echarts.min.js}">script>
    <script th:src="@{/js/echarts-wordcloud.min.js}">script>
head>
<body>
<div th:replace="header::html">div>
<div class="container">
    <div class="card border-light" id="SearchCardShow" style="position:absolute;left: 50%;top:50%;transform: translate(-50%,-75%);width: 60%">
        <div class="card-body" >
            <div class="input-group" >
                <input type="text" class="form-control" aria-describedby="SendSearchContent" id="SearchContent">
                <div class="input-group-append">
                    <button class="btn btn-dark" type="button" id="SendSearchContent">搜索button>
                div>
            div>
            <div class="container mt-3" id="articleTables" style="text-align: center">
            div>
            <div id="WordCloud" style="width: auto;height:200px;">div>
        div>
    div>
div>
<div th:replace="footer::html">div>
<script th:src="@{/js/header.js}">script>
<script th:src="@{/js/articleList.js}">script>



<script>
    readUserInfo();
    var chart=echarts.init(document.getElementById('WordCloud'));
    function createRandomItemStyle() {
        return {
            normal: {
                color: 'rgb(' + [
                    Math.round(Math.random() * 160),
                    Math.round(Math.random() * 160),
                    Math.round(Math.random() * 160)
                ].join(',') + ')'
            }
        };
    }
    function generateRequireData(data) {
        var chartData=[];
        for(var i in data){
            chartData.push({name:data[i].content,value:data[i].times,textStyle: createRandomItemStyle()});
        }
        return chartData;
    }
    function loadWordCloudChart(data,chart){
        option = {
            tooltip: {
                show: true
            },
            series: [{
                name: 'Search Trends',
                type: 'wordCloud',
                size: ['80%', '80%'],
                textRotation : [0, 45, 90, -45],
                textPadding: 0,
                autoSize: {
                    enable: true,
                    minSize: 14
                },
                data:generateRequireData(data)
            }]
        };
        chart.setOption(option);
    }

    function setSearchShowList(status){
        if(status){
            $("#SearchCardShow").css("position","absolute");
            $("#SearchCardShow").css("left","50%");
            $("#SearchCardShow").css("transform","translate(-50%,-75%)");
            $("#SearchCardShow").css("top","50%");
            $("#SearchCardShow").css("width","60%");
        }else{
            $("#SearchCardShow").css("position","");
            $("#SearchCardShow").css("left","");
            $("#SearchCardShow").css("transform","");
            $("#SearchCardShow").css("top","");
            $("#SearchCardShow").css("width","");
        }
    }
    var myStatus=true;
    $(document).ready(function () {
        updateFooter(1);
        $.get("/article/getSearchHistory",function (data,status) {
           if(data){
               // console.log(data);
               loadWordCloudChart(data,chart);
           }

        });
        $("#SendSearchContent").click(function () {
            if($("#SearchContent").val()){
                $.post("/article/searchArticle",{
                    contents:$("#SearchContent").val()
                },function (data,status) {
                    if(data){
                        //console.log(data);
                        setSearchShowList(false);
                        updateArticleList(data);
                        updateFooter(data.length);
                        $("#WordCloud").hide();
                    }
                });
            }
        });
    });


script>
body>
html>

需要注意的是文字颜色从之前的itemStyle变成了textStyle,而官方文档还是itemStyle

结果

SpringBoot博客开发日常记录-搜索功能以及搜索词汇云图显示_第1张图片

你可能感兴趣的:(JavaWeb)