一、ArticleMapper接口中增加搜索功能
// 根据文章标题搜索文章
@Select("SELECT * FROM t_article WHERE title like CONCAT('%',#{title},'%')")
public List<Article> selectArticleByTitle(String title);
二、IArticleService接口中增加搜索功能
// 根据文章标题搜索文章
public List<Article> selectArticleByTitle(String title);
三、ArticleServiceImpl实现类中增加搜索功能
@Override
public List<Article> selectArticleByTitle(String title) {
List<Article> list = articleMapper.selectArticleByTitle(title);
for (Article article : list) {
Statistic statistic = statisticMapper.selectStatisticWithArticleId(article.getId());
article.setHits(statistic.getHits());
}
return list;
}
四、IndexController增加处理搜索请求的方法
// 根据文章标题搜索
@GetMapping(value = "/search")
public String index(HttpServletRequest request, String titleKey) {
// 获取标题中包含titleKey的所有文章
List<Article> articleList = articleServiceImpl.selectArticleByTitle(titleKey);
request.setAttribute("articleList", articleList);
return "client/searchResults";
}
五、在templates/client下增加searchResults.html模板页
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!-- 载入文章头部页面,位置在/client文件夹下的header模板页面,模板名称th:fragment为header -->
<div th:replace="/client/header::header('我的博客',null)"></div>
<body>
<div class="am-g am-g-fixed blog-fixed index-page">
<!-- 搜索结果 -->
<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>
<div style="text-align: left">
<th:block th:each="article :${articleList}">
<a style="font-size: 15px;" th:href="@{'/article/'+${article.id}}"
th:text="${articleStat.index+1}+'、'+${article.title}+'('+${article.hits}+')'">
</a>
<hr style="margin-top: 0.6rem;margin-bottom: 0.4rem" />
</th:block>
</div>
</div>
</div>
</div>
</body>
<!-- 载入文章尾部页面,位置在/client文件夹下的footer模板页面,模板名称th:fragment为footer -->
<div th:replace="/client/footer::footer"></div>
</html>
六、修改前台的header.html,提交搜索关键字
<script type="text/javascript">
function search(){
var title = $('#search-inp').val();
//alert(title);
//window.location.href='/search/'+title;
$("#searchForm").submit();
}
</script>
<div class="navbar-search" >
<span class="icon-search" onclick="search()"></span>
<form id="searchForm" role="search" th:action="@{/search}"><!-- onsubmit="return false;" -->
<span class="search-box">
<input type="text" id="search-inp" name="titleKey" class="input" th:placeholder="${keywords ?: '搜索...'}" maxlength="30"
autocomplete="off"/>
</span>
</form>
</div>