lucene(全文搜索)_luceneweb例子

先来看看效果图:

由于我没"D:\opt\lucene\index",所以不能搜索出东东...

下载地址:

http://apache.dataguru.cn/lucene/java/2.9.4/

lucene-2.9.4-src.zip (包含源码)

lucene-2.9.4.zip

项目结构:

=======================================================

源码部分

=======================================================

/luceneweb/WebContent/configuration.jsp

 1 <!--
 2     Licensed to the Apache Software Foundation (ASF) under one or more
 3     contributor license agreements.  See the NOTICE file distributed with
 4     this work for additional information regarding copyright ownership.
 5     The ASF licenses this file to You under the Apache License, Version 2.0
 6     the "License"); you may not use this file except in compliance with
 7     the License.  You may obtain a copy of the License at
 8  
 9         http://www.apache.org/licenses/LICENSE-2.0
10  
11     Unless required by applicable law or agreed to in writing, software
12     distributed under the License is distributed on an "AS IS" BASIS,
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14     See the License for the specific language governing permissions and
15     limitations under the License.
16  -->
17 <%
18 /* Author: Andrew C. Oliver (acoliver2@users.sourceforge.net) */
19 String appTitle = "Apache Lucene Example - Intranet Server Search Application";
20 /* make sure you point the below string to the index you created with IndexHTML */
21 String indexLocation = "/opt/lucene/index";
22 String appfooter = "Apache Lucene Template WebApp 1.0";
23 %>

/luceneweb/WebContent/footer.jsp

 1 <!--
 2     Licensed to the Apache Software Foundation (ASF) under one or more
 3     contributor license agreements.  See the NOTICE file distributed with
 4     this work for additional information regarding copyright ownership.
 5     The ASF licenses this file to You under the Apache License, Version 2.0
 6     the "License"); you may not use this file except in compliance with
 7     the License.  You may obtain a copy of the License at
 8  
 9         http://www.apache.org/licenses/LICENSE-2.0
10  
11     Unless required by applicable law or agreed to in writing, software
12     distributed under the License is distributed on an "AS IS" BASIS,
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14     See the License for the specific language governing permissions and
15     limitations under the License.
16  -->
17 <% /* Author Andrew C. Oliver (acoliver2@users.sourceforge.net) */ %>
18 <p align="center">
19     <%=appfooter%>
20 </p>
21 </body>
22 </html>

/luceneweb/WebContent/header.jsp

 1 <!--
 2     Licensed to the Apache Software Foundation (ASF) under one or more
 3     contributor license agreements.  See the NOTICE file distributed with
 4     this work for additional information regarding copyright ownership.
 5     The ASF licenses this file to You under the Apache License, Version 2.0
 6     the "License"); you may not use this file except in compliance with
 7     the License.  You may obtain a copy of the License at
 8  
 9         http://www.apache.org/licenses/LICENSE-2.0
10  
11     Unless required by applicable law or agreed to in writing, software
12     distributed under the License is distributed on an "AS IS" BASIS,
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14     See the License for the specific language governing permissions and
15     limitations under the License.
16  -->
17 <%@include file="configuration.jsp"%>
18 <% /* Author: Andrew C. Oliver (acoliver2@users.sourceforge.net */ %>
19 <html>
20 <head>
21     <title><%=appTitle%></title>
22 </head>
23 <body>
24 
25 <p align="center">
26 Welcome to the Lucene Template application. (This is the header)
27 </p>

/luceneweb/WebContent/index.jsp

 1 <!--
 2     Licensed to the Apache Software Foundation (ASF) under one or more
 3     contributor license agreements.  See the NOTICE file distributed with
 4     this work for additional information regarding copyright ownership.
 5     The ASF licenses this file to You under the Apache License, Version 2.0
 6     the "License"); you may not use this file except in compliance with
 7     the License.  You may obtain a copy of the License at
 8  
 9         http://www.apache.org/licenses/LICENSE-2.0
10  
11     Unless required by applicable law or agreed to in writing, software
12     distributed under the License is distributed on an "AS IS" BASIS,
13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14     See the License for the specific language governing permissions and
15     limitations under the License.
16  -->
17 <%@include file="header.jsp"%>
18 <% /* Author: Andrew C. Oliver (acoliver2@users.sourceforge.net) */ %>
19 <center> 
20     <form name="search" action="results.jsp" method="get">
21         <p>
22             <input name="query" size="44"/>&nbsp;Search Criteria
23         </p>
24         <p>
25             <input name="maxresults" size="4" value="100"/>&nbsp;Results Per Page&nbsp;
26             <input type="submit" value="Search"/>
27         </p>
28         </form>
29 </center>
30 <%@include file="footer.jsp"%>

/luceneweb/WebContent/results.jsp

  1 <!--
  2     Licensed to the Apache Software Foundation (ASF) under one or more
  3     contributor license agreements.  See the NOTICE file distributed with
  4     this work for additional information regarding copyright ownership.
  5     The ASF licenses this file to You under the Apache License, Version 2.0
  6     the "License"); you may not use this file except in compliance with
  7     the License.  You may obtain a copy of the License at
  8  
  9         http://www.apache.org/licenses/LICENSE-2.0
 10  
 11     Unless required by applicable law or agreed to in writing, software
 12     distributed under the License is distributed on an "AS IS" BASIS,
 13     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14     See the License for the specific language governing permissions and
 15     limitations under the License.
 16  -->
 17 <%@ page import="javax.servlet.*, javax.servlet.http.*, java.io.*, org.apache.lucene.analysis.*, org.apache.lucene.analysis.standard.StandardAnalyzer, org.apache.lucene.document.*, org.apache.lucene.index.*, org.apache.lucene.store.*, org.apache.lucene.search.*, org.apache.lucene.queryParser.*, org.apache.lucene.demo.*, org.apache.lucene.demo.html.Entities, java.net.URLEncoder, org.apache.lucene.util.Version"%>
 18 
 19 <%
 20     /*
 21      Author: Andrew C. Oliver, SuperLink Software, Inc. (acoliver2@users.sourceforge.net)
 22 
 23      This jsp page is deliberatly written in the horrible java directly embedded 
 24      in the page style for an easy and concise demonstration of Lucene.
 25      Due note...if you write pages that look like this...sooner or later
 26      you'll have a maintenance nightmare.  If you use jsps...use taglibs
 27      and beans!  That being said, this should be acceptable for a small
 28      page demonstrating how one uses Lucene in a web app. 
 29 
 30      This is also deliberately overcommented. ;-)
 31 
 32      */
 33 %>
 34 <%!public String escapeHTML(String s) {
 35         s = s.replaceAll("&", "&amp;");
 36         s = s.replaceAll("<", "&lt;");
 37         s = s.replaceAll(">", "&gt;");
 38         s = s.replaceAll("\"", "&quot;");
 39         s = s.replaceAll("'", "&apos;");
 40         return s;
 41     }%>
 42 <%@include file="header.jsp"%>
 43 <%
 44     boolean error = false; //used to control flow for error messages
 45     String indexName = indexLocation; //local copy of the configuration variable
 46     IndexSearcher searcher = null; //the searcher used to open/search the index
 47     Query query = null; //the Query created by the QueryParser
 48     TopDocs hits = null; //the search results
 49     int startindex = 0; //the first index displayed on this page
 50     int maxpage = 50; //the maximum items displayed on this page
 51     String queryString = null; //the query entered in the previous page
 52     String startVal = null; //string version of startindex
 53     String maxresults = null; //string version of maxpage
 54     int thispage = 0; //used for the for/next either maxpage or
 55                         //hits.totalHits - startindex - whichever is
 56                         //less
 57 
 58     try {
 59         IndexReader reader = IndexReader.open(FSDirectory.open(new File(indexName)), true); // only searching, so read-only=true
 60         searcher = new IndexSearcher(reader); //create an indexSearcher for our page
 61                                                 //NOTE: this operation is slow for large
 62                                                 //indices (much slower than the search itself)
 63                                                 //so you might want to keep an IndexSearcher 
 64                                                 //open
 65 
 66     } catch (Exception e) { //any error that happens is probably due
 67                             //to a permission problem or non-existant
 68                             //or otherwise corrupt index
 69 %>
 70 <p>ERROR opening the Index - contact sysadmin!</p>
 71 <p>
 72   Error message:
 73   <%=escapeHTML(e.getMessage())%></p>
 74 <%
 75     error = true; //don't do anything up to the footer
 76     }
 77 %>
 78 <%
 79     if (error == false) { //did we open the index?
 80         queryString = request.getParameter("query"); //get the search criteria
 81         startVal = request.getParameter("startat"); //get the start index
 82         maxresults = request.getParameter("maxresults"); //get max results per page
 83         try {
 84             maxpage = Integer.parseInt(maxresults); //parse the max results first
 85             startindex = Integer.parseInt(startVal); //then the start index  
 86         } catch (Exception e) {
 87         } //we don't care if something happens we'll just start at 0
 88             //or end at 50
 89 
 90         if (queryString == null)
 91             throw new ServletException("no query " + //if you don't have a query then
 92                     "specified"); //you probably played on the 
 93                                     //query string so you get the 
 94                                     //treatment
 95 
 96         Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); //construct our usual analyzer
 97         try {
 98             QueryParser qp = new QueryParser("contents", analyzer);
 99             query = qp.parse(queryString); //parse the 
100         } catch (ParseException e) { //query and construct the Query
101                                         //object
102                                         //if it's just "operator error"
103                                         //send them a nice error HTML
104 %>
105 <p>
106   Error while parsing query:
107   <%=escapeHTML(e.getMessage())%></p>
108 <%
109     error = true; //don't bother with the rest of
110                             //the page
111         }
112     }
113 %>
114 <%
115     if (error == false && searcher != null) { // if we've had no errors
116                                                 // searcher != null was to handle
117                                                 // a weird compilation bug 
118         thispage = maxpage; // default last element to maxpage
119         hits = searcher.search(query, maxpage + startindex); // run the query 
120         if (hits.totalHits == 0) { // if we got no results tell the user
121 %>
122 <p>I'm sorry I couldn't find what you were looking for.</p>
123 <%
124     error = true; // don't bother with the rest of the
125                             // page
126         }
127     }
128 
129     if (error == false && searcher != null) {
130 %>
131 <table>
132   <tr>
133     <td>Document</td>
134     <td>Summary</td>
135   </tr>
136   <%
137       if ((startindex + maxpage) > hits.totalHits) {
138               thispage = hits.totalHits - startindex; // set the max index to maxpage or last
139           } // actual search result whichever is less
140 
141           for (int i = startindex; i < (thispage + startindex); i++) { // for each element
142   %>
143   <tr>
144     <%
145         Document doc = searcher.doc(hits.scoreDocs[i].doc); //get the next document 
146                 String doctitle = doc.get("title"); //get its title
147                 String url = doc.get("path"); //get its path field
148                 if (url != null && url.startsWith("../webapps/")) { // strip off ../webapps prefix if present
149                     url = url.substring(10);
150                 }
151                 if ((doctitle == null) || doctitle.equals("")) //use the path if it has no title
152                     doctitle = url;
153                 //then output!
154     %>
155     <td><a href="<%=url%>"><%=doctitle%></a></td>
156     <td><%=doc.get("summary")%></td>
157   </tr>
158   <%
159       }
160   %>
161   <%
162       if ((startindex + maxpage) < hits.totalHits) { //if there are more results...display 
163                                                           //the more link
164 
165               String moreurl = "results.jsp?query=" + URLEncoder.encode(queryString) + //construct the "more" link
166                       "&amp;maxresults=" + maxpage + "&amp;startat=" + (startindex + maxpage);
167   %>
168   <tr>
169     <td></td>
170     <td><a href="<%=moreurl%>">More Results>></a></td>
171   </tr>
172   <%
173       }
174   %>
175 </table>
176 
177 <%
178     } //then include our footer.
179     if (searcher != null)
180         searcher.close();
181 %>
182 <%@include file="footer.jsp"%>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏技术墨客

Spring-boot特性(2) 原

在使用Spring-boot时,永远要记住它仅仅是Spring Framework的延伸(或者说整合),其底层还是基于Spring Framework(core...

2532
来自专栏Java技术栈

@Controller,@Service,@Repository,@Component详解。

@Controller 用来表示一个web控制层bean,如SpringMvc中的控制器。 @Service 用来表示一个业务层bean。 @Repositor...

3775
来自专栏木制robot技术杂谈

Python中os.path.dirname(__file__)的用法

os.path.dirname()的用途 os.path.dirname()用来获取文件的路径。 如: 1 2>>> os.path.dirname('/ho...

4107
来自专栏JAVA高级架构

Spring 知识点提炼

1. Spring框架的作用 轻量:Spring是轻量级的,基本的版本大小为2MB 控制反转:Spring通过控制反转实现了松散耦合,对象们给出它们的依赖,...

4019
来自专栏菩提树下的杨过

spring cloud 学习(4) - hystrix 服务熔断处理

hystrix 是一个专用于服务熔断处理的开源项目,当依赖的服务方出现故障不可用时,hystrix有一个所谓的断路器,一但打开,就会直接拦截掉对故障服务的调用,...

2115
来自专栏CSDN技术头条

Spring Data REST 与 Spring RestTemplate 实战详解

这篇分为两部分内容进行介绍(Spring Data REST 和 Spring RestTemplate)。我之前有一篇文章完整的介绍了 HTTP 协议的内容,...

9675
来自专栏微信公众号:Java团长

Spring知识点提炼

Sping的容器可以分为两种类型 1. BeanFactory:(org.springframework.beans.factory.BeanFactory接...

1372
来自专栏小筱月

springboot 整合 MongoDB 实现登录注册,html 页面获取后台参数的方法

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而...

3200
来自专栏WindCoder

Spring基础小结

Spring是一个开源的轻量级Java SE(Java 标准版本)/Java EE(Java 企业版本)开发应用框架,其目的是用于简化企业级应用程序开发。

621
来自专栏阿杜的世界

Spring Boot:定制自己的starter

在学习Spring Boot的过程中,接触最多的就是starter。可以认为starter是一种服务——使得使用某个功能的开发者不需要关注各种依赖库的处理,不需...

1240

扫码关注云+社区

领取腾讯云代金券