lucene3.0 分页显示与高亮显示(转)

25 篇文章 0 订阅
分页类

 

Java代码 复制代码  收藏代码
  1. package com.cee.com;   
  2.   
  3. import java.util.List;   
  4.   
  5. //分页类   
  6. public class PageBean {   
  7.   
  8.     private List list; // 要返回的某一页的记录列表   
  9.     private int allRow; // 总记录数   
  10.     private int totalPage; // 总页数   
  11.     private int currentPage; // 当前页   
  12.     private int pageSize; // 每页记录数   
  13.     private int offset;   
  14.   
  15.     public int getOffset() {   
  16.         return offset;   
  17.     }   
  18.   
  19.     public void setOffset(int offset) {   
  20.         this.offset = offset;   
  21.     }   
  22.   
  23.     private boolean isFirstPage; // 是否为第一页   
  24.     private boolean isLastPage; // 是否为最后一页   
  25.     private boolean hasPreviousPage; // 是否有前一页   
  26.     private boolean hasNextPage; // 是否有下一页   
  27.   
  28.     public List getList() {   
  29.         return list;   
  30.     }   
  31.   
  32.     public void setList(List list) {   
  33.         this.list = list;   
  34.     }   
  35.   
  36.     public int getAllRow() {   
  37.         return allRow;   
  38.     }   
  39.   
  40.     public void setAllRow(int allRow) {   
  41.         this.allRow = allRow;   
  42.     }   
  43.   
  44.     public int getTotalPage() {   
  45.         int totalPage = allRow % pageSize == 0 ? allRow / pageSize : allRow   
  46.                 / pageSize + 1;   
  47.         return totalPage;   
  48.     }   
  49.   
  50.     public void setTotalPage(int totalPage) {   
  51.         this.totalPage = totalPage;   
  52.     }   
  53.   
  54.     public int getCurrentPage() {   
  55.         return currentPage;   
  56.     }   
  57.   
  58.     public void setCurrentPage(int currentPage) {   
  59.         this.currentPage = currentPage;   
  60.     }   
  61.   
  62.     public int getPageSize() {   
  63.         return pageSize;   
  64.     }   
  65.   
  66.     public void setPageSize(int pageSize) {   
  67.         this.pageSize = pageSize;   
  68.     }   
  69.   
  70.     /** */  
  71.     /**  
  72.      * 初始化分页信息  
  73.      */  
  74.     public void init() {   
  75.         this.isFirstPage = isFirstPage();   
  76.         this.isLastPage = isLastPage();   
  77.         this.hasPreviousPage = isHasPreviousPage();   
  78.         this.hasNextPage = isHasNextPage();   
  79.     }   
  80.   
  81.     /** */  
  82.     /**  
  83.      * 以下判断页的信息,只需getter方法(is方法)即可  
  84.      *   
  85.      * @return  
  86.      */  
  87.   
  88.     public boolean isFirstPage() {   
  89.         return currentPage == 1// 如是当前页是第1页   
  90.     }   
  91.   
  92.     public boolean isLastPage() {   
  93.         return currentPage == totalPage; // 如果当前页是最后一页   
  94.     }   
  95.   
  96.     public boolean isHasPreviousPage() {   
  97.         return currentPage != 1// 只要当前页不是第1页   
  98.     }   
  99.   
  100.     public boolean isHasNextPage() {   
  101.   if(totalPage==0){   
  102.    return false;   
  103.   }else{   
  104.    return currentPage != totalPage; // 只要当前页不是最后1页   
  105.   }   
  106.      
  107.  } /** */  
  108.     /**  
  109.      * 计算总页数,静态方法,供外部直接通过类名调用  
  110.      *   
  111.      * @param pageSize  
  112.      *            每页记录数  
  113.      * @param allRow  
  114.      *            总记录数  
  115.      * @return 总页数  
  116.      */  
  117.     public static int countTotalPage(final int pageSize, final int allRow) {   
  118.         int totalPage = allRow % pageSize == 0 ? allRow / pageSize : allRow   
  119.                 / pageSize + 1;   
  120.         return totalPage;   
  121.     }   
  122.   
  123.     /** */  
  124.     /**  
  125.      * 计算当前页开始记录  
  126.      *   
  127.      * @param pageSize  
  128.      *            每页记录数  
  129.      * @param currentPage  
  130.      *            当前第几页  
  131.      * @return 当前页开始记录号  
  132.      */  
  133.     public static int countOffset(final int pageSize, final int currentPage) {   
  134.         final int offset = pageSize * (currentPage - 1);   
  135.         return offset;   
  136.     }   
  137.   
  138.     /** */  
  139.     /**  
  140.      * 计算当前页,若为0或者请求的URL中没有"?page=",则用1代替  
  141.      *   
  142.      * @param page  
  143.      *            传入的参数(可能为空,即0,则返回1)  
  144.      * @return 当前页  
  145.      */  
  146.     public static int countCurrentPage(int page) {   
  147.         final int curPage = (page == 0 ? 1 : page);   
  148.         return curPage;   
  149.     }   
  150.   
  151.     public static int lastSqlIdx(int rowStartIdx, int pageSize) {   
  152.         return rowStartIdx + pageSize;   
  153.     }   
  154. }  
package com.cee.com;

import java.util.List;

//分页类
public class PageBean {

	private List list; // 要返回的某一页的记录列表
	private int allRow; // 总记录数
	private int totalPage; // 总页数
	private int currentPage; // 当前页
	private int pageSize; // 每页记录数
	private int offset;

	public int getOffset() {
		return offset;
	}

	public void setOffset(int offset) {
		this.offset = offset;
	}

	private boolean isFirstPage; // 是否为第一页
	private boolean isLastPage; // 是否为最后一页
	private boolean hasPreviousPage; // 是否有前一页
	private boolean hasNextPage; // 是否有下一页

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

	public int getAllRow() {
		return allRow;
	}

	public void setAllRow(int allRow) {
		this.allRow = allRow;
	}

	public int getTotalPage() {
		int totalPage = allRow % pageSize == 0 ? allRow / pageSize : allRow
				/ pageSize + 1;
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	/** */
	/**
	 * 初始化分页信息
	 */
	public void init() {
		this.isFirstPage = isFirstPage();
		this.isLastPage = isLastPage();
		this.hasPreviousPage = isHasPreviousPage();
		this.hasNextPage = isHasNextPage();
	}

	/** */
	/**
	 * 以下判断页的信息,只需getter方法(is方法)即可
	 * 
	 * @return
	 */

	public boolean isFirstPage() {
		return currentPage == 1; // 如是当前页是第1页
	}

	public boolean isLastPage() {
		return currentPage == totalPage; // 如果当前页是最后一页
	}

	public boolean isHasPreviousPage() {
		return currentPage != 1; // 只要当前页不是第1页
	}

	public boolean isHasNextPage() {
  if(totalPage==0){
   return false;
  }else{
   return currentPage != totalPage; // 只要当前页不是最后1页
  }
  
 }	/** */
	/**
	 * 计算总页数,静态方法,供外部直接通过类名调用
	 * 
	 * @param pageSize
	 *            每页记录数
	 * @param allRow
	 *            总记录数
	 * @return 总页数
	 */
	public static int countTotalPage(final int pageSize, final int allRow) {
		int totalPage = allRow % pageSize == 0 ? allRow / pageSize : allRow
				/ pageSize + 1;
		return totalPage;
	}

	/** */
	/**
	 * 计算当前页开始记录
	 * 
	 * @param pageSize
	 *            每页记录数
	 * @param currentPage
	 *            当前第几页
	 * @return 当前页开始记录号
	 */
	public static int countOffset(final int pageSize, final int currentPage) {
		final int offset = pageSize * (currentPage - 1);
		return offset;
	}

	/** */
	/**
	 * 计算当前页,若为0或者请求的URL中没有"?page=",则用1代替
	 * 
	 * @param page
	 *            传入的参数(可能为空,即0,则返回1)
	 * @return 当前页
	 */
	public static int countCurrentPage(int page) {
		final int curPage = (page == 0 ? 1 : page);
		return curPage;
	}

	public static int lastSqlIdx(int rowStartIdx, int pageSize) {
		return rowStartIdx + pageSize;
	}
}

 

 分页代码与高亮代码

 

  注意 indexDir 目录下存放的是 lucene 的索引, 直接运行代码会发生错误,请看上篇文章生成索引

 

Java代码 复制代码  收藏代码
  1. package com.cee.test;   
  2.   
  3. import java.io.File;   
  4. import java.io.IOException;   
  5. import java.io.StringReader;   
  6. import java.util.ArrayList;   
  7. import java.util.Date;   
  8. import java.util.List;   
  9.   
  10. import org.apache.lucene.analysis.Analyzer;   
  11. import org.apache.lucene.analysis.TokenStream;   
  12. import org.apache.lucene.analysis.standard.StandardAnalyzer;   
  13. import org.apache.lucene.document.Document;   
  14. import org.apache.lucene.index.CorruptIndexException;   
  15. import org.apache.lucene.queryParser.MultiFieldQueryParser;   
  16. import org.apache.lucene.queryParser.ParseException;   
  17. import org.apache.lucene.search.IndexSearcher;   
  18. import org.apache.lucene.search.Query;   
  19. import org.apache.lucene.search.ScoreDoc;   
  20. import org.apache.lucene.search.Searcher;   
  21. import org.apache.lucene.search.TopScoreDocCollector;   
  22. import org.apache.lucene.search.highlight.Highlighter;   
  23. import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;   
  24. import org.apache.lucene.search.highlight.QueryScorer;   
  25. import org.apache.lucene.search.highlight.SimpleHTMLFormatter;   
  26. import org.apache.lucene.store.FSDirectory;   
  27. import org.apache.lucene.util.Version;   
  28.   
  29. import com.cee.com.PageBean;   
  30.   
  31. /**  
  32.  * 分页与高亮显示  
  33.  *   
  34.  * @author qcy  
  35.  *   
  36.  */  
  37. public class PageSearcher {   
  38.   
  39.     /**  
  40.      *   
  41.      * @param pageNo  
  42.      * @param pageSize  
  43.      * @param q  
  44.      *            表示查询条件  
  45.      * @return  
  46.      */  
  47.     public final static String indexDir = "d:\\TestLucene\\indexDB";   
  48.   
  49.     @SuppressWarnings({ "unchecked""unchecked""deprecation""deprecation" })   
  50.     public static PageBean getPageQuery(int pageNo, int pageSize, String[] q)   
  51.             throws CorruptIndexException, IOException, ParseException, InvalidTokenOffsetsException {   
  52.         List result = new ArrayList();   
  53.         Searcher searcher = new IndexSearcher(FSDirectory.open(new File(   
  54.                 indexDir)), true);   
  55.         Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);   
  56.         String[] fields = { "cbs""zz" };   
  57.         Query query = MultiFieldQueryParser.parse(Version.LUCENE_CURRENT, q,   
  58.                 fields, analyzer);   
  59.   
  60.         TopScoreDocCollector topCollector = TopScoreDocCollector.create(   
  61.                 searcher.maxDoc(), false);   
  62.         searcher.search(query, topCollector);   
  63.         // 高亮设置   
  64.         SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter(   
  65.                 "<B>""</B>");//   
  66.         Highlighter highlighter = new Highlighter(simpleHtmlFormatter,   
  67.                 new QueryScorer(query));   
  68.   
  69.         // 查询当页的记录   
  70.         ScoreDoc[] docs = topCollector.topDocs((pageNo - 1) * pageSize,   
  71.                 pageSize).scoreDocs;   
  72.         for (ScoreDoc scdoc : docs) {   
  73.             Document document = searcher.doc(scdoc.doc);   
  74.             TokenStream tokenStream = analyzer.tokenStream("text",   
  75.                     new StringReader(document.get("cbs")));   
  76.             String str = highlighter.getBestFragment(tokenStream, document.get("cbs"));     
  77.             result.add("id=" + document.get("id") + "|cbs="  
  78.                     + document.get("cbs") + "|zz=" + document.get("zz")+"|red"+str);   
  79.   
  80.         }   
  81.         PageBean pb = new PageBean();   
  82.         pb.setCurrentPage(pageNo);// 当前页   
  83.         pb.setPageSize(pageSize);   
  84.         pb.setAllRow(topCollector.getTotalHits());// hit中的记录数目   
  85.         pb.setList(result);   
  86.         return pb;   
  87.   
  88.     }   
  89.   
  90.     public static void main(String[] args) throws CorruptIndexException,   
  91.             IOException, ParseException, InvalidTokenOffsetsException {   
  92.         String[] q = { "中国""外国" };   
  93.         long start = new Date().getTime();   
  94.         PageBean pb = getPageQuery(14, q);   
  95.         System.out.println("页面内容-------开始---");   
  96.         List pgResult = pb.getList();   
  97.         for (int i = 0; i < pgResult.size(); i++) {   
  98.             System.out.println(pgResult.get(i).toString());   
  99.         }   
  100.         System.out.println("页面内容-------结束---");   
  101.         System.out.println("当前页号 " + pb.getCurrentPage());   
  102.         System.out.println("是否是第一个页? " + pb.isFirstPage());   
  103.         System.out.println("是否是最后页? " + pb.isLastPage());   
  104.         System.out.println("存在上一页? " + pb.isHasPreviousPage());   
  105.         System.out.println("存在下一页? " + pb.isHasNextPage());   
  106.         System.out.println("每页的记录数 " + pb.getPageSize());   
  107.         System.out.println("总页数 " + pb.getTotalPage());   
  108.         System.out.println("总记录数 " + pb.getAllRow());   
  109.         long end = new Date().getTime();   
  110.         System.out.println("花费时间:" + (double) (end - start) / 1000 + "秒");   
  111.   
  112.     }   
  113.   
  114. }  
package com.cee.test;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Searcher;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.cee.com.PageBean;

/**
 * 分页与高亮显示
 * 
 * @author qcy
 * 
 */
public class PageSearcher {

	/**
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param q
	 *            表示查询条件
	 * @return
	 */
	public final static String indexDir = "d:\\TestLucene\\indexDB";

	@SuppressWarnings({ "unchecked", "unchecked", "deprecation", "deprecation" })
	public static PageBean getPageQuery(int pageNo, int pageSize, String[] q)
			throws CorruptIndexException, IOException, ParseException, InvalidTokenOffsetsException {
		List result = new ArrayList();
		Searcher searcher = new IndexSearcher(FSDirectory.open(new File(
				indexDir)), true);
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
		String[] fields = { "cbs", "zz" };
		Query query = MultiFieldQueryParser.parse(Version.LUCENE_CURRENT, q,
				fields, analyzer);

		TopScoreDocCollector topCollector = TopScoreDocCollector.create(
				searcher.maxDoc(), false);
		searcher.search(query, topCollector);
		// 高亮设置
		SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter(
				"<B>", "</B>");//
		Highlighter highlighter = new Highlighter(simpleHtmlFormatter,
				new QueryScorer(query));

		// 查询当页的记录
		ScoreDoc[] docs = topCollector.topDocs((pageNo - 1) * pageSize,
				pageSize).scoreDocs;
		for (ScoreDoc scdoc : docs) {
			Document document = searcher.doc(scdoc.doc);
			TokenStream tokenStream = analyzer.tokenStream("text",
					new StringReader(document.get("cbs")));
			String str = highlighter.getBestFragment(tokenStream, document.get("cbs"));  
			result.add("id=" + document.get("id") + "|cbs="
					+ document.get("cbs") + "|zz=" + document.get("zz")+"|red"+str);

		}
		PageBean pb = new PageBean();
		pb.setCurrentPage(pageNo);// 当前页
		pb.setPageSize(pageSize);
		pb.setAllRow(topCollector.getTotalHits());// hit中的记录数目
		pb.setList(result);
		return pb;

	}

	public static void main(String[] args) throws CorruptIndexException,
			IOException, ParseException, InvalidTokenOffsetsException {
		String[] q = { "中国", "外国" };
		long start = new Date().getTime();
		PageBean pb = getPageQuery(1, 4, q);
		System.out.println("页面内容-------开始---");
		List pgResult = pb.getList();
		for (int i = 0; i < pgResult.size(); i++) {
			System.out.println(pgResult.get(i).toString());
		}
		System.out.println("页面内容-------结束---");
		System.out.println("当前页号 " + pb.getCurrentPage());
		System.out.println("是否是第一个页? " + pb.isFirstPage());
		System.out.println("是否是最后页? " + pb.isLastPage());
		System.out.println("存在上一页? " + pb.isHasPreviousPage());
		System.out.println("存在下一页? " + pb.isHasNextPage());
		System.out.println("每页的记录数 " + pb.getPageSize());
		System.out.println("总页数 " + pb.getTotalPage());
		System.out.println("总记录数 " + pb.getAllRow());
		long end = new Date().getTime();
		System.out.println("花费时间:" + (double) (end - start) / 1000 + "秒");

	}

}
 

 

分页类有个小bug

 

 分页的前台scrip

 

Js代码 复制代码  收藏代码
  1. function changepage(pid){   
  2.         var url="";   
  3.         if(pid=='1'){   
  4.             window.location=url+"&page=1";   
  5.         }   
  6.         if(pid=='2'){   
  7.             window.location=url+"&page=${dataList.currentPage-1}";   
  8.         }   
  9.         if(pid=='3'){   
  10.             window.location=url+"&page=${dataList.currentPage+1}";   
  11.         }   
  12.         if(pid=='4'){   
  13.             window.location=url+"&page=${dataList.totalPage}";   
  14.         }   
  15.     }  
function changepage(pid){
	    var url="";
	    if(pid=='1'){
	    	window.location=url+"&page=1";
	    }
	    if(pid=='2'){
	    	window.location=url+"&page=${dataList.currentPage-1}";
	    }
	    if(pid=='3'){
	    	window.location=url+"&page=${dataList.currentPage+1}";
	    }
	    if(pid=='4'){
	   		window.location=url+"&page=${dataList.totalPage}";
	    }
	}

 前台分页java

 

 

 

Html代码 复制代码  收藏代码
  1. <table>  
  2. <tr>  
  3. <td>  
  4. <table>  
  5. <c:forEach items="${dataList.list}" var="m"> ${m}</c:forEach>  
  6. </table>  
  7. </td>  
  8. </tr>  
  9. <tr>  
  10. <td>  
  11. <table width="100%" border="0" cellspacing="2" cellpadding="0">  
  12.                         <tr>  
  13.                             <td height="25" align="center">  
  14.                                 <div id="page" class="txt_p">  
  15.                                     共${dataList.totalPage}页   
  16.                                     <c:choose>  
  17.                                         <c:when test="${dataList.hasPreviousPage}">  
  18.                                             <a href="javascript:changepage('1')">首页</a>  
  19.                                             <a href="javascript:changepage('2')"> <img  
  20.                                                     src="${skinPath}images/hygl/left_h.gif" align="absmiddle"  
  21.                                                     border="0" /> </a>  
  22.                                             <a href="javascript:changepage('2')">上一页</a>  
  23.                                         </c:when>  
  24.                                         <c:otherwise>  
  25.                                             首页   
  26.                                         <img src="${skinPath}images/hygl/left_b.gif" align="absmiddle" />上一页   
  27.                                         </c:otherwise>  
  28.                                     </c:choose>  
  29.                                     第${dataList.currentPage}页   
  30.                                     <c:choose>  
  31.                                         <c:when test="${dataList.hasNextPage}">  
  32.                                             <a href="javascript:changepage('3')">下一页</a>  
  33.                                             <a href="javascript:changepage('3')"> <img  
  34.                                                     src="${skinPath}images/hygl/right_h.gif" align="absmiddle"  
  35.                                                     border="0" /> </a>  
  36.                                             <a href="javascript:changepage('4')">尾页</a>  
  37.                                         </c:when>  
  38.                                         <c:otherwise>  
  39.                                               下一页<img  
  40.                                                 src="${skinPath}images/hygl/right_b.gif" align="absmiddle" />尾页   
  41.                                          </c:otherwise>  
  42.                                     </c:choose>  
  43.                                 </div>  
  44.                             </td>  
  45.                         </tr>  
  46.                     </table>  
  47. </td>  
  48. </tr>  
  49.   
  50. </table>  
<table>
<tr>
<td>
<table>
<c:forEach items="${dataList.list}" var="m"> ${m}</c:forEach>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%" border="0" cellspacing="2" cellpadding="0">
						<tr>
							<td height="25" align="center">
								<div id="page" class="txt_p">
									共${dataList.totalPage}页
									<c:choose>
										<c:when test="${dataList.hasPreviousPage}">
											<a href="javascript:changepage('1')">首页</a>
											<a href="javascript:changepage('2')"> <img
													src="${skinPath}images/hygl/left_h.gif" align="absmiddle"
													border="0" /> </a>
											<a href="javascript:changepage('2')">上一页</a>
										</c:when>
										<c:otherwise>
											首页
										<img src="${skinPath}images/hygl/left_b.gif" align="absmiddle" />上一页
										</c:otherwise>
									</c:choose>
									第${dataList.currentPage}页
									<c:choose>
										<c:when test="${dataList.hasNextPage}">
											<a href="javascript:changepage('3')">下一页</a>
											<a href="javascript:changepage('3')"> <img
													src="${skinPath}images/hygl/right_h.gif" align="absmiddle"
													border="0" /> </a>
											<a href="javascript:changepage('4')">尾页</a>
										</c:when>
										<c:otherwise>
                                              下一页<img
												src="${skinPath}images/hygl/right_b.gif" align="absmiddle" />尾页
                                         </c:otherwise>
									</c:choose>
								</div>
							</td>
						</tr>
					</table>
</td>
</tr>

</table>
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值