代码改变世界

solr开发 小案例

2017-04-09 14:05  甘雨路  阅读(826)  评论(0编辑  收藏  举报

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
      
      <!-- 设置编码 -->
      <filter>
        <filter-name>charset</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>charset</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
      
      <!-- springmvc核心配置 -->
      <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 配置springmvc核心文件的路径 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.test</url-pattern>
    </servlet-mapping>
  

</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
    <!-- 包扫描 -->
    <context:component-scan base-package="zr.com"/>
    <!-- 开启SpringMVC的相关注解 -->
    <mvc:annotation-driven/>
    
    <!-- 视图解析器 -->
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
</beans>
package zr.com.pojo;

public class Info {
    
    private String id;
    
    private String courseID;
    
    private String courseName;
    
    private String courseContent;
    
    private String schoolName;
    
    private String schoolShortName;
    
    private String classID;
    
    private String className;
    
    private String courseprice;
    
    private String courseAreaID;
    
    private String areaName;
    
    private String OrderNum;
    
    private String HotScoreAvg;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCourseID() {
        return courseID;
    }

    public void setCourseID(String courseID) {
        this.courseID = courseID;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public String getCourseContent() {
        return courseContent;
    }

    public void setCourseContent(String courseContent) {
        this.courseContent = courseContent;
    }

    public String getSchoolName() {
        return schoolName;
    }

    public void setSchoolName(String schoolName) {
        this.schoolName = schoolName;
    }

    public String getSchoolShortName() {
        return schoolShortName;
    }

    public void setSchoolShortName(String schoolShortName) {
        this.schoolShortName = schoolShortName;
    }

    public String getClassID() {
        return classID;
    }

    public void setClassID(String classID) {
        this.classID = classID;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getCourseprice() {
        return courseprice;
    }

    public void setCourseprice(String courseprice) {
        this.courseprice = courseprice;
    }

    public String getCourseAreaID() {
        return courseAreaID;
    }

    public void setCourseAreaID(String courseAreaID) {
        this.courseAreaID = courseAreaID;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public String getOrderNum() {
        return OrderNum;
    }

    public void setOrderNum(String orderNum) {
        OrderNum = orderNum;
    }

    public String getHotScoreAvg() {
        return HotScoreAvg;
    }

    public void setHotScoreAvg(String hotScoreAvg) {
        HotScoreAvg = hotScoreAvg;
    }

    public Info() {
        super();
    }

    public Info(String id, String courseID, String courseName,
            String courseContent, String schoolName, String schoolShortName,
            String classID, String className, String courseprice,
            String courseAreaID, String areaName, String orderNum,
            String hotScoreAvg) {
        super();
        this.id = id;
        this.courseID = courseID;
        this.courseName = courseName;
        this.courseContent = courseContent;
        this.schoolName = schoolName;
        this.schoolShortName = schoolShortName;
        this.classID = classID;
        this.className = className;
        this.courseprice = courseprice;
        this.courseAreaID = courseAreaID;
        this.areaName = areaName;
        OrderNum = orderNum;
        HotScoreAvg = hotScoreAvg;
    }

    @Override
    public String toString() {
        return "Info [id=" + id + ", courseID=" + courseID + ", courseName="
                + courseName + ", courseContent=" + courseContent
                + ", schoolName=" + schoolName + ", schoolShortName="
                + schoolShortName + ", classID=" + classID + ", className="
                + className + ", courseprice=" + courseprice
                + ", courseAreaID=" + courseAreaID + ", areaName=" + areaName
                + ", OrderNum=" + OrderNum + ", HotScoreAvg=" + HotScoreAvg
                + "]";
    }
    
    
}
package zr.com.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.junit.Test;

import zr.com.pojo.Info;

public class SearchUtil {
    
    private static SolrServer server;
    
    static{
        server = new HttpSolrServer("http://192.168.10.105:18080");
    }
    /**
     *  查询
     * @throws SolrServerException
     */
    public static List<Info> queryTest(String queryString,int star,int size) throws SolrServerException{
        
        List<Info> infos = new ArrayList<Info>();
        
        // 建立请求
//        SolrServer server = new HttpSolrServer("http://192.168.10.105:18080");
        // 创建查询对象
        SolrQuery query = new SolrQuery();
        // 查询语句的处理(模糊查询,添加双引号即可)
        String queryStr = queryString;
        
        // 设置高亮显示
        // 是否设置高亮
        query.setHighlight(true);
        // 前缀
        query.setHighlightSimplePre("<em>");
        // 后缀
        query.setHighlightSimplePost("</em>");
        // 设置高亮文本的长度
        query.setHighlightFragsize(8);
        query.setHighlightRequireFieldMatch(true);
        // 设置高亮的字段
        query.addHighlightField("courseName");
        
        query.setQuery(queryStr);
        
        // 分页(起始位置)
        query.setStart(star);
        // 分页(每一页显示的条数)
        query.setRows(size);
//        // 排序(降序)
//        query.setSort("courseName", ORDER.desc);
        
        //执行查询
        QueryResponse response = server.query(query);
        // 获取高亮的信息
        Map<String, Map<String, List<String>>> map = response.getHighlighting();
        
        System.out.println(map);
        
        //执行查询
//        QueryResponse response = server.query(query);
        // 获取响应后的结果集
        SolrDocumentList list = response.getResults();
        for (SolrDocument solrDocument : list) {
            // 获取ID
            String id = SearchUtil.dealNull(solrDocument, "id");
            String courseID = SearchUtil.dealNull(solrDocument, "courseID");
            String courseName = SearchUtil.dealNull(solrDocument, "courseName");
            String courseContent = SearchUtil.dealNull(solrDocument, "courseContent");
            String schoolName = SearchUtil.dealNull(solrDocument, "schoolName");
            String schoolShortName = SearchUtil.dealNull(solrDocument, "schoolShortName");
            String classID = SearchUtil.dealNull(solrDocument, "classID");
            String className = SearchUtil.dealNull(solrDocument, "className");
            String courseprice = SearchUtil.dealNull(solrDocument, "courseprice");
            String courseAreaID = SearchUtil.dealNull(solrDocument, "courseAreaID");
            String areaName = SearchUtil.dealNull(solrDocument, "areaName");
            String OrderNum = SearchUtil.dealNull(solrDocument, "OrderNum");
            String HotScoreAvg = SearchUtil.dealNull(solrDocument, "HotScoreAvg");
            // 高亮替换
            Map<String, List<String>> hlisMap = map.get(id);
            if (hlisMap!=null) {
//                System.out.println(hlisMap);
                Object cName = hlisMap.get("courseName");
                if (cName!=null) {
                    // 替换
                    courseName = cName.toString();
                }
            }
            Info info = new Info(id, courseID, courseName, courseContent, schoolName, schoolShortName, classID, className, courseprice, courseAreaID, areaName, OrderNum, HotScoreAvg);
            infos.add(info);
//            System.out.println("id:"+id+",courseName:"+courseName+",schoolShortName:"+schoolShortName);
        }
        return infos;
    }
    
    /**
     * 处理空异常
     * @return
     */
    private static String dealNull(SolrDocument solrDocument,String field){
        String fieldValue = null;
        if (solrDocument.getFieldValue(field) != null) {
            fieldValue = solrDocument.getFieldValue(field).toString();
        }
        return fieldValue;
    }
}
package zr.com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;

import zr.com.pojo.Info;
import zr.com.util.SearchUtil;

/**
 * 
 * @author lf
 *
 */
@Controller
public class SolrController {
    /**
     * 进入search页面
     * @return
     */
    @RequestMapping("/lf")
    public String comeInPage(){
        return "search";
    }
    
    /**
     * 获取数据
     * @param paramter
     * @param request
     * @param response
     * @throws SolrServerException
     * @throws IOException 
     */
    @RequestMapping(value="search",method=RequestMethod.GET)
    public void getData(String paramter,HttpServletRequest request,HttpServletResponse response) 
            throws SolrServerException, IOException{
        // 设置编码
//        request.setCharacterEncoding("utf-8");
//        response.setCharacterEncoding("utf-8");
        System.out.println("准备获取相关数据...");
        System.out.println("paramter:"+paramter);
        String query = "courseName:"+paramter;    
        // 获取响应的数据数据
        List<Info> infos = SearchUtil.queryTest(query,0,10);
        // 遍历
//        for (Info info : infos) {
//            System.out.println(info);
//        }
        //设置文本类型的编码为UTF-8
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String jsonString = JSON.toJSONString(infos);
        
        // 输出
        out.print(jsonString);
        out.flush();
        out.close();
        
        System.out.println(jsonString);
    }
    
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>搜索引擎</title>
</head>
<body>
    <br><br><br>
    <div>
        <input id="search" placeholder="请输入你要搜索的内容" />
        <button onclick="getData()">搜索</button>
        <br>
        <table id="table">
        </table>
    
        
    </div>
    <style type="text/css">
         em {color:red;}
        
    </style>
    <script type="text/javascript">
        
        // 异步请求
        function getData(){
            
            var value = document.getElementById("search").value;
            
            // 创建请求对象
             var request = new XMLHttpRequest();
            // 请求方式
            var method = "GET";
            // 链接
            var url = "search.test?paramter="+value;
            /* alert(url); */
            // 初始化参数
            request.open(method, url, true);
            // 发送请求
            request.send(null);
            request.onreadystatechange = function(){
                // 如果响应请求
                if(request.status==200 || request.status == 304){
                    var text = request.responseText;
                    var jsonData = eval("("+text+")");
                    // 获取table
                    var table = document.getElementById("table");
                    /* alert(jsonData); */
                    // 清除table的数据
                    var rowNum=table.rows.length;
                    for (var i=0;i<rowNum;i++)
                    {
                        
                        table.deleteRow(i);
                        rowNum=rowNum-1;
                        i=i-1;
                    }
                    // 添加数据
                    for(var i = 0;i < jsonData.length;i++ ){
                        // 添加行
                        var row = table.insertRow();
                        // 添加单元格
                        var cell = row.insertCell();
                        // 设置内容
                        cell.innerHTML = jsonData[i]["areaName"]+jsonData[i]["className"]
                                        +jsonData[i]["courseAreaID"]+jsonData[i]["courseContent"]
                                        +jsonData[i]["courseID"]+jsonData[i]["courseName"]
                                        +jsonData[i]["courseprice"]+jsonData[i]["hotScoreAvg"]
                                        +jsonData[i]["id"]+jsonData[i]["orderNum"]
                                        +jsonData[i]["schoolName"]+jsonData[i]["schoolShortName"]
                                        +jsonData[i]["classID"]+jsonData[i]["className"]
                                        +jsonData[i]["courseAreaID"]+jsonData[i]["HotScoreAvg"];
                    }
                    
                }  
            };
             
            
        }
    
    </script>
    
</body>
</html>