zoukankan      html  css  js  c++  java
  • solr综合案例

    1.  综合案例

    1.1. 需求

    使用Solr实现电商网站中商品信息搜索功能,可以根据关键字、分类、价格搜索商品信息,也可以根据价格进行排序,并且实现分页功能。

    界面如下:

    1.2分析

    开发人员需要的文档:静态页面(根据UI设计由美工给出)、数据库设计、原型设计

    1.2.1 UI 分析

    1.2.2    架构分析

     

    架构分为:

    (1)、solr服务器。(已经做完,同入门示例)

    (2)、自己开发的应用(重点)

    (3)、数据库mysql

    自己开发的应用

    Controller      负责和前端页面进行请求和响应的交互

    Service        封装查询条件,调用dao。

    Dao           搜索索引库,返回搜索结果。

    1.3. 环境准备

    Solr:4.10.3

    Jdk环境:1.7.0_72(solr4.10 不能使用jdk1.7以下)

    Ide环境:Eclipse

    Web服务器(servlet容器):Tomcat 7+

    1.4   代码实现

    1.4.1. 实现步骤

    第一部分:SpringMVC框架搭建

    第二部分:整合Spring与Solr (Solr服务已经搭建好了)

    第三部分:实现功能

    1.4.2. 实现步骤

    1.4.2.1. 第一部分:SpringMVC框架搭建

    --新建一个动态网站项目导入SpringMVC的Jar包

    第一步:导入SpringMVC依赖包

    1.4.2.2..     第二步:创建一个请求页面
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html>
     4 <html>
     5 <head>
     6 <meta charset="UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10    
    11    <a href="${pageContext.request.contextPath }/say">say hello</a>
    12 </body>
    13 </html>
    1.4.2.3     第三步:web.xml配置(入口)
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     3     xmlns="http://xmlns.jcp.org/xml/ns/javaee"
     4     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
     5     id="WebApp_ID" version="3.1">
     6     <display-name>solr-demo-02-jd</display-name>
     7     <!-- 配置编码过滤器 -->
     8     <filter>
     9         <filter-name>characterEncodingFilter</filter-name>
    10         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    11         <!-- 指定编码 -->
    12         <init-param>
    13             <param-name>encoding</param-name>
    14             <param-value>UTF-8</param-value>
    15         </init-param>
    16     </filter>
    17     <filter-mapping>
    18         <filter-name>characterEncodingFilter</filter-name>
    19         <url-pattern>/*</url-pattern>
    20     </filter-mapping>
    21     <!-- 核心控制器 -->
    22     <servlet>
    23         <servlet-name>dispatcherServlet</servlet-name>
    24         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    25         <!-- 读取指定的配置文件 -->
    26         <init-param>
    27             <param-name>contextConfigLocation</param-name>
    28             <param-value>classpath:spring-*.xml</param-value>
    29         </init-param>
    30         <!-- 随web server启动 -->
    31         <load-on-startup>1</load-on-startup>
    32     </servlet>
    33     <servlet-mapping>
    34         <servlet-name>dispatcherServlet</servlet-name>
    35         <url-pattern>/</url-pattern>
    36     </servlet-mapping>
    37 
    38 </web-app>
    1.4.2.4     第四步:配置Spring配置文件
     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <beans xmlns="http://www.springframework.org/schema/beans"
     3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4     xmlns:mvc="http://www.springframework.org/schema/mvc"
     5     xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
     6         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
     7         
     8         <!-- 启动注解默认支持 -->
     9         <mvc:annotation-driven />
    10         <!-- 放开默认静态资源访问 -->
    11         <mvc:default-servlet-handler/>
    12         
    13         <!-- 配置视图解释器 -->
    14         <mvc:view-resolvers>
    15           <mvc:jsp prefix="/" suffix=".jsp"/>
    16         </mvc:view-resolvers>
    17 
    18 
    19 </beans>

    --context配置文件,spring-context.xml

    <?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: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-4.3.xsd">
            
            <!-- 扫描组件配置 -->
            <context:component-scan base-package="org.chu"></context:component-scan>
    
    
    </beans>
    1.4.2.5   第五步:配置业务控制器
     1 @Controller
     2 public class PageController {
     3     
     4     @RequestMapping(value="/{page}")
     5     public String showPage(@PathVariable String page) {
     6         System.out.println("-HelloWorld:"+page);
     7         return page;
     8     }
     9 
    10 }
    1.4.2.6     第六步:配置返回页面
     1 <%@ page language="java" contentType="text/html; charset=UTF-8"
     2     pageEncoding="UTF-8"%>
     3 <!DOCTYPE html>
     4 <html>
     5 <head>
     6 <meta charset="UTF-8">
     7 <title>Insert title here</title>
     8 </head>
     9 <body>
    10   你好世界
    11 </body>
    12 </html>

     第二部分:整合Spring与Solr

    注意事项:

    必须要将Solr的Tomcat服务器的端口配置与项目运行的Tomcat的端口不一样。因为如果在同一个电脑上同时运行两个Tomcat,端口不修改就会冲突。

       第一步:修改Solr服务器端口

    前提:Solr服务器已经准备好。

    --Tomcat的conf/server.xml文件中,修改端口

    --tomcat端口说明:

       8005:关机端口, 修改为:8006

       8080:默认服务端口,修改为 :8888

       8009:请求转向端口,修改为:8010

    第二步:导入Solr的连接依赖包

    --将以下的jar 加入到项目的WEB-INF/lib里面。

    --日志处理包

    --solrj依赖包

       第三步:加入Log4j的支持

    在classpath根目录加入lo4j.properties。该文件可以在solr的包里面找到

    第四步:在spring-context.xml配置Solr
    <!-- 配置Solr整合的连接对象 -->
    <bean name="solrServer" class="org.apache.solr.client.solrj.impl.HttpSolrServer">
         <!-- 通过构造方法指定请求的路径 -->
        <constructor-arg index="0" value="http://localhost:8888/solr/soreCore0225" />
    </bean>

     

     第三部分:功能实现

    第一步:导入页面资源

    --将准备的资料放在webapp,网站根目录。并且删除原来测试的页面,test.jsp以及say.jsp。

    结果如下:

    第二步:导入JSTL的支持

    第三步:编写JavaBean
     1 public class Product {
     2     // 商品编号
     3     private String pid;
     4     // 商品名称
     5     private String name;
     6     // 商品分类名称
     7     private String catalogName;
     8     // 价格
     9     private double price;
    10     // 商品描述
    11     private String description;
    12     // 图片名称
    13     private String picture;
    14   //补全get、set方法
    15 }

    --业务模型(Value Object VO),编写ResultModel业务模型

     1 import java.util.List;
     2 
     3 public class ResultModel {
     4     
     5     private List<Product> productList;
     6     // 商品总数
     7     private Long recordCount;
     8     // 总页数
     9     private int pageCount;
    10     // 当前页
    11     private int currentPage;
    12   //补全get、set方法
    13 
    14 }
        第四步:获得Solr的数据
     1 import java.util.ArrayList;
     2 import java.util.List;
     3 import org.apache.solr.client.solrj.SolrQuery;
     4 import org.apache.solr.client.solrj.impl.HttpSolrServer;
     5 import org.apache.solr.client.solrj.response.QueryResponse;
     6 import org.apache.solr.common.SolrDocument;
     7 import org.apache.solr.common.SolrDocumentList;
     8 import org.chu.dao.ProductDAO;
     9 import org.chu.pojo.Product;
    10 import org.chu.pojo.ResultModel;
    11 import org.springframework.beans.factory.annotation.Autowired;
    12 import org.springframework.stereotype.Repository;
    13 @Repository
    14 public class ProductDAOImpl implements ProductDAO{
    15     @Autowired
    16     private HttpSolrServer solrServer;
    17     @Override
    18     public ResultModel queryProduct(SolrQuery query) throws Exception {
    19         
    20         //创建一个返回的业务模型对象
    21         ResultModel resultModel=new ResultModel();
    22         //第一步:获得Solr响应对象
    23         QueryResponse response = solrServer.query(query);
    24         //第二步:获得返回的结果集
    25         SolrDocumentList results = response.getResults();
    26         //第三步:将SolrDocumentList集合对象转成List<Product>
    27         List<Product> products=new ArrayList<>();
    28         // 设置高亮信息
    29         Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
    30         for (SolrDocument solrDocument : results) {
    31             Product product=new Product();
    32             product.setPid((String)solrDocument.get("id"));
    33 // 设置高亮信息
    34     List<String> list = highlighting.get(solrDocument.get("id")).get("product_name");
    35             
    36             String prodName = (String) solrDocument.get("product_name");
    37             if (list != null)prodName = list.get(0);
    38             product.setName(prodName);
    39             product.setCatalogName((String) solrDocument.get("product_catalog_name"));
    40             product.setPicture((String) solrDocument.get("product_picture"));
    41             product.setDescription((String) solrDocument.get("product_description"));
    42             product.setPrice((Double) solrDocument.get("product_price"));
    43             products.add(product);
    44         }
    45         //第四步:将数据封装到ResultModel
    46         //总记录书
    47         resultModel.setRecordCount(results.getNumFound());
    48         //查询的的结果
    49         resultModel.setProductList(products);
    50         return resultModel;
    51     }
    52 }
    第五步:构造Service
    import org.apache.solr.client.solrj.SolrQuery;
    import org.apache.solr.client.solrj.SolrQuery.ORDER;
    import org.chu.dao.ProductDAO;
    import org.chu.pojo.ResultModel;
    import org.chu.service.ProductService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    @Service
    public class ProductServiceImpl implements ProductService {
        
        @Autowired
        private ProductDAO productDAO;
    
        @Override
        public ResultModel queryProduct(String queryString, String cataName, String price, String sort, Integer curPage)
                throws Exception {
            //构建查询的条件
            SolrQuery query=new SolrQuery();
            
            //判断关键字不为空
            if (queryString!=null&&!"".equals(queryString)) {
    
                query.set("q", queryString);
            }else {
                query.set("q", "*:*");
            }
            
            //增加过滤条件
            if (cataName!=null&&!"".equals(cataName)) {
                query.addFilterQuery("product_catalog_name:"+cataName);
            }
            
            //价格过滤
            if (price!=null&&!"".equals(price)) {
                String[] prices = price.split("-");
                query.addFilterQuery("product_price:[ "+prices[0]+" TO "+prices[1]+" ]");
            }
            
            //排序,1:desc ,非1就,asc
            if (sort!=null&&sort.equals("1")) {
                query.setSort("product_price", ORDER.desc);
            }else{
                query.setSort("product_price", ORDER.asc);
            }
            
            //设置分页
            //如果没有值,就为第一页
            if (curPage==null) {
                curPage=1;
            }
            //设置查询的开始位置
            query.setStart((curPage-1)*20);
            //设置每页记录数
            query.setRows(20);
            
            
            query.set("df", "product_name");
            
            //高亮分词设置
            query.setHighlight(true);
            //设置高亮的字段
            query.addHighlightField("product_name");
            //通过标签设置颜色
            
            //开始标签
            query.setHighlightSimplePre("<font style="color:red">");
            query.setHighlightSimplePost("</font>");
            
            
            ResultModel resultModel = productDAO.queryProduct(query);
            
            //返回结果后,封装请求的数据到业务模型里面
            resultModel.setCurrentPage(curPage);
            
            // 总页数 = 总数量 / 每页数据条数  结果向上取整
            double ceil = Math.ceil(resultModel.getRecordCount().doubleValue()/20);
            resultModel.setPageCount((int)ceil);
    
            
            return resultModel;
        }
    
    }
     构建Controller
    import org.chu.pojo.ResultModel;
    import org.chu.service.ProductService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    public class ProductController {
        
        @Autowired
        private ProductService productService;
        
        @RequestMapping(value="/list")
        public String list(String queryString, @RequestParam("catalog_name") String catalogName,String price, String sort, Integer curPage, ModelMap model) {
            try {
                ResultModel resultModel = productService.queryProduct(queryString, catalogName, price, sort, curPage);
                model.addAttribute("result", resultModel);
                
                model.addAttribute("queryString", queryString);
                model.addAttribute("catalog_name", catalogName);
                model.addAttribute("price", price);
                model.addAttribute("sort", sort);
                model.addAttribute("page", curPage);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            
          return "product_list";    
        }
    
    }
  • 相关阅读:
    Oracle索引
    Oracle Union Union All 对查询结果集操作
    Oracle表连接
    BIOS + MBR > UEFI + GPT
    Opensource Licenses
    Linux 系统下使用dd命令备份还原MBR主引导记录
    Linux 文件类型笔记
    Linux 分支那么多,这里可以帮你缩小选择范围
    Arch Linux 的休眠设置
    Arch Linux pacman 与其他发行版操作比较
  • 原文地址:https://www.cnblogs.com/vieta/p/11219134.html
Copyright © 2011-2022 走看看