solr开发 小案例

<?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>
时间: 2024-10-10 02:39:53

solr开发 小案例的相关文章

iOS开发小案例之根据年份判断生肖

写这篇博客,首先感谢林永坚Jake,我是看了林老师的视频课程,写了这篇博客,十分感谢. 需求是这样的,用户输入年份,点击按钮,然后根据该年份判断生肖,并显示一张生肖的图片.具体开发步骤如下: (1)首先准备12张图片,代表12个生肖.图片编号分别为 0--11 (2)在Main.storyboard中拖入3个控件,Text Field输入年份,Button点击确认,ImageView显示生肖图片.界面如下: . (3)按住control键和鼠标左键,选择outlets,拖动输入框和图片控件到.s

20160410javaweb 开发小案例 --客户管理系统

客户管理系统---体验基于数据库javaweb的增删改查 添加客户 查询客户列表 修改客户信息 删除客户 条件查询客户信息 分页查询客户 javaee的经典三层架构--工厂类实现解耦 jsp+servlet+service+dao+jdbc+mysql+c3p0+dbutils com.dzq.web .service .dao .domain .util .exception .factory JSTL mysql驱动 beanutils c3p0包 dbutils包 confing.prop

广播小案例-监听系统网络状态 --Android开发

本例通过广播实现简单的监听系统网络状态改变的小案例. 1.案例效果演示 当手机连网后,系统提示“已连接网络”, 当手机断网后,系统提示“当前网络不可用1”. 2.案例实现 在主活动中动态注册广播,然后写一个内部类来接收系统广播,下面是相关文件的核心代码: MainActivity.java: public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private Networ

Windows Server之浅谈SMB以及SMB小案例分享

SMB由来 服务器消息区块(英语:Server Message Block,缩写为SMB,服务器消息区块),又称网络文件共享系统(英语:Common Internet File System,缩写为CIFS),一种应用层网络传输协议,由微软开发,主要功能是使网络上的机器能够计算机文件.打印机.串行端口和通讯等资源.它也提供经认证的进程间通信机能.它主要用在装有Microsoft Windows的机器上,在这样的机器上被称为Microsoft Windows Network. SMB版本 OS W

Thinkphp 生成订单号小案例

Thinkphp 生成订单号小案例小伙伴们在日常的商城项目开发中,都会遇到订单号生成的问题,今天呢思梦PHP就带领大家去解读一下生成订单号的问题!首先,订单号我们要明确它有有3个性质:1.唯一性 2.不可推测性 3.效率性,唯一性和不可推测性不用说了,效率性是指不能频繁的去数据库查询以避免重复.况且满足这些条件的同时订单号还要足够的短.不知道小伙伴们在日常的项目中是否也和我一样去思考过生成订单的一些小问题,可能你也会说,这些东西不用想的那么复杂,其实呢,小编也是同意大家的看法,但是殊不知我们做程

Cookie小案例-----记住浏览过的商品记录

Cookie小案例------记住浏览过的商品记录 我们知道,这个功能在电商项目中很常见.这里处理请求和页面显示都是由servlet实现,主要是为了体现cookie的作用, 实现功能如下: 1,点击购买的商品后,显示到另一页面 2,记住用户浏览过的商品,并在页面时中显示 3,当浏览过的数量超过最大值限度时,最下面一个商品被挤下去 4,当浏览过的商品本身就在浏览记录中,显示列表将其从中间移到最上面 显示一打开网站的样子和显示用户的浏览记录: package cn.itcast.cookie; im

Session小案例-----简单购物车的使用

Session小案例-----简单购物车的使用 同上篇一样,这里的处理请求和页面显示同样用的都是servlet. 功能实现如下: 1,显示网站的所有商品 2,用户点击购买后,能够记住用户选择的商品 3,实现了多个会话共享一个session 4, 实现了浏览器禁用cookie后数据共享问题的处理 首页: package cn.itcast.shopping; import java.io.IOException; import java.io.PrintWriter; import java.io

Session小案例------完成用户登陆

Session小案例------完成用户登陆 在项目开发中,用户登陆功能再寻常不过啦,当用户完成用户名和密码校验后,进入主界面,需要在主界面中显示用户的信息,此时用session来记住用户是最为合适不过了. 功能实现如下: 1,完成用户登陆功能 2,在主界面记住用户 3,完成用户注销功能 用户类: package cn.itcast.login; public class User{ private String username; private String password; public

两个小案例

今天收获了两个小案例.其实对工作都很有启发,把案例和心得在这里记录下来,希望对别人也有帮助. 案例1: 测试人员在测试系统发现在系统A和系统B之间通过总线通讯,偶尔会出现timeout现象.反馈开发后,开发难以重现.根据简要分析后,认为是测试系统性能不行,拍胸脯保证在生产系统,用于系统通讯的总线不会出现这种问题.测试人员加强了性能测试强度,发现硬件提高后,的确性能测试场景中未能重现timeout.最终否决了缺陷.结果上到生产上后,timeout又出现了,而且对核心业务产生了一定影响(多亏有补救办