solr7.4和springMVC和freemarker集成
applicationContext-web.xml中
<context:component-scan base-package="com.jinlin" />
<!-- 放行靜態文件 -->
<mvc:default-servlet-handler />
<!-- 啟用註解 -->
<mvc:annotation-driven />
<!-- freemarker配置 -->
<bean id="freeMarkerConfigurer"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="" />
<property name="freemarkerSettings">
<props>
<prop key="tag_syntax">auto_detect</prop>
<prop key="template_update_delay">1</prop>
<prop key="defaultEncoding">UTF-8</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="boolean_format">true,false</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="time_format">HH:mm:ss</prop>
<prop key="number_format">0.######</prop>
<prop key="whitespace_stripping">true</prop>
<prop key="auto_import">/WEB-INF/ftl/spring.ftl as s</prop>
</props>
</property>
</bean>
<!-- freemarker視圖解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".html" />
<!-- 解決亂碼問題 -->
<property name="contentType" value="text/html; charset=UTF-8" />
</bean>
dao層
package com.jinlin.dao;
import java.util.Map;
import org.apache.solr.client.solrj.SolrQuery;
public interface NovelDao {
public Map<String, Object> novelIndex(SolrQuery query)throws Exception;
}
dao實現類
package com.jinlin.dao.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.jinlin.dao.NovelDao;
import com.jinlin.entity.Novel;
@Component
public class NovelDaoImpl implements NovelDao {
@Override
public Map<String, Object> NovelIndex(SolrQuery query) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
SolrClient httpSolrClient = new HttpSolrClient.Builder("http://localhost:9999/solr/test").build();
//執行搜索
QueryResponse queryResponse = httpSolrClient.query(query);
//獲取結果集
SolrDocumentList docs = queryResponse.getResults();
//得到高亮數據
Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
List<Novel> list = new ArrayList<Novel>();
if(docs != null && !docs.isEmpty()) {
//遍歷結果集
for(SolrDocument doc : docs) {
Novel novel = new Novel();
novel.setId(Integer.parseInt(String.valueOf(doc.get("id"))));
List<String> all = highlighting.get(doc.get("id")).get("name");
if (all == null || all.isEmpty()) {
novel.setName(String.valueOf(doc.get("name")));
}else{
novel.setName(String.valueOf(all.get(0)));
}
all = highlighting.get(doc.get("id")).get("author");
if (all == null || all.isEmpty()) {
novel.setAuthor(String.valueOf(doc.get("author")));
}else{
novel.setAuthor(String.valueOf(all.get(0)));
}
novel.setNtype(String.valueOf(doc.get("ntype")));
novel.setNsize(Long.parseLong(String.valueOf(doc.get("nsize"))));
all = highlighting.get(doc.get("id")).get("info");
if (all == null || all.isEmpty()) {
novel.setInfo(String.valueOf(doc.get("info")));
}else{
novel.setInfo(String.valueOf(all.get(0)));
}
novel.setNurl(String.valueOf(doc.get("nurl")));
list.add(novel);
}
}
//獲取總條數
long total = docs.getNumFound();
map.put("list",list);
map.put("total",total);
return map;
}
}
service層
package com.jinlin.service;
import java.util.Map;
public interface NovelService {
public Map<String, Object> NovelIndex(String keywords, String nsize, String sort, Integer currentPage, Integer lineSize) throws Exception;
}
service實現類
package com.jinlin.service.impl;
import java.util.Map;
import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jinlin.dao.NovelDao;
import com.jinlin.service.NovelService;
@Service
public class NovelServiceImpl implements NovelService {
@Autowired
private NovelDao ndi;
@Override
public Map<String, Object> NovelIndex(String keywords, String nsize, String sort, Integer currentPage,
Integer lineSize) throws Exception {
SolrQuery query = new SolrQuery();
//設置默認查詢域
query.set("df","keywords");
//設置查詢關鍵字
if (keywords != null && !"".equals(keywords)) {
query.setQuery(keywords);
}else{
query.setQuery("*:*");
}
if (nsize != null && !"".equals(nsize)) {
//設置查詢大小區間
query.setFilterQueries("nsize:" + nsize);
}
if (sort != null && "".equals(sort)) {
//設置排序
if ("asc".equals(sort)){
query.setSort("sort", SolrQuery.ORDER.asc);
}else{
query.setSort("sort", SolrQuery.ORDER.desc);
}
}
//設置分頁
query.setStart(currentPage);
query.setRows(lineSize);
//設置高亮
query.setHighlight(true);
query.setHighlightSimplePre("<span style=‘color:red‘>");
query.setHighlightSimplePost("</span>");
query.addHighlightField("name");
query.addHighlightField("author");
query.addHighlightField("info");
Map<String, Object> all = ndi.NovelIndex(query);
long total = Long.parseLong(String.valueOf(all.get("total")));
//得到總頁數
long pageSize = (total + lineSize - 1)/lineSize;
all.put("pageSize",pageSize);
return all;
}
}
controller層
package com.jinlin.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.jinlin.service.NovelService;
@Controller
@RequestMapping()
public class IndexController {
@Autowired
private NovelService nsi;
@RequestMapping("/index")
public ModelAndView indexController(@RequestParam(required=false)String keywords,@RequestParam(required=false)String nsize,@RequestParam(required=false)String sort,@RequestParam(required=false)Integer currentPage) {
ModelAndView mav = new ModelAndView("index");
if(currentPage == null) {
currentPage = 1;
}
Integer lineSize = 10;
try {
Map<String, Object> indexMap = nsi.NovelIndex(keywords, nsize, sort, currentPage, lineSize);
mav.addObject("res",indexMap);
mav.addObject("keywords",keywords);
mav.addObject("nsize",nsize);
mav.addObject("sort",sort);
mav.addObject("page",currentPage);
} catch (Exception e) {
e.printStackTrace();
}
return mav;
}
}
spring.ftl
<#-- 設置context全局變量 springMacroRequestContext.getContextUrl("") -->
<#assign base = springMacroRequestContext.getContextUrl("")>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="${s.base}/css/index.css" />
<script src="${s.base}/js/jquery-3.2.1.min.js"></script>
<title>首頁</title>
</head>
<body>
<!-- 登錄彈出層 -->
<div class="cvs" style="display: none" id="cvs2_logon">
<div class="newModWin">
<div class="title">登錄愛下下賬號</div>
<div class="close" id="cvs2_close" onclick="close_win()">X</div>
<div class="logWin">
<form action="" method="post" id="form">
<input type="text" class="inp user" name="name" autocomplete="off"
placeholder="請輸入用戶名" /> <input type="password" class="inp pass"
name="password" autocomplete="off" placeholder="請輸入密碼" /> <a
href="findpass.html" class="find_pass">忘記密碼,立即找回</a> <input
type="submit" class="su_btn" value="登錄" /> <a
href="register.html" class="reg">註冊</a>
</form>
</div>
</div>
</div>
<div class="header">
<div class="lf">
<a href="index.html">首頁</a> <a href="bbs.html">論壇</a> <a
href="upload.html">上傳資料</a> <a href="project.html">項目管理</a>
</div>
<div class="rf">
<a href="personal.html">個人信息</a> <a href="shoucang.html">我的收藏</a> <a
href="point.html">積分</a> <a>退出登錄</a>
</div>
</div>
<!-- 網站頭信息-->
<div id="nav">
<div id="search">
<input type="text" id="keywords" name="name" /> <a class="btn"
onclick="searchNovel()">搜索<a />
</div>
<div id="logon">
<div class="cons">歡迎光臨愛下下!</div>
<div class="opers">
<a class="btn" href="upload.html">上傳資料<a />
</div>
</div>
<div id="login">
<a href="javascript:void(0)" onclick="showWin()">點擊登錄</a>
</div>
</div>
<p></p>
<!-- 網站主體 -->
<div id="main">
<#if res?exists> <#list res.list as novel> <!-- 定義一個條目-->
<div class="pro" id="${novel.id}">
<div class="img">
<img src="${s.base}/images/txt.svg" />
</div>
<div class="cs">
<div class="up">
<a href="${novel.nurl}">${novel.name}</a>
</div>
<div class="down">
作者:${novel.author} <b>內容簡介:${novel.info}</b>
</div>
</div>
<div class="arr">
大小:<span>${novel.nsize}</span>
</div>
</div>
</#list> </#if>
<div class="panigation">
<a onclick="goto(1)">首頁</a> <a onclick="goto(${page-1})"><上一頁</a>
<a onclick="goto(${page+1})">下一頁></a> <a
onclick="goto(${res.pageSize})">尾頁></a> ${page}/${res.pageSize}
</div>
</div>
<script>
function showWin() {
$("#cvs2_logon").fadeIn();
}
function close_win() {
$("#cvs2_logon").fadeOut();
}
</script>
</body>
<script>
function searchFt(){
var fm = $("#form");
fm.submit();
}
function showWin(){
$("#cvs2_logon").fadeIn();
}
function close_win(){
$("#cvs2_logon").fadeOut();
}
function goto(n){
$("[form=fms]").val(n);
searchFt();
}
function searchNovel(){
var keywords = $("#keywords").val();
window.location = "index.html?keywords=" + keywords;
}
</script>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!-- spring監聽器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-dao.xml</param-value>
</context-param>
<!-- springMVC核心配置 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-web.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- 編碼過濾器 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
solr7.4和springMVC和freemarker集成