码迷,mamicode.com
首页 > Web开发 > 详细

Jsp +Js + Jquery + EasyUI + Servlet + Lucene,完成分页

时间:2018-12-03 19:59:10      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:time()   去掉   click   显示   encoding   style   override   opd   input   

package loaderman.fy.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

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

import loaderman.fy.entity.Page;
import loaderman.fy.service.ArticleService;
import net.sf.json.JSONArray;


public class ArticleServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        this.doPost(request,response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        try {

            request.setCharacterEncoding("UTF-8");

            //获取关键字
            String keywords = request.getParameter("keywords");//培训
            if(keywords == null || keywords.trim().length()==0){
                keywords = "培训";//默认值
            }

            //获取当前页号
            String temp = request.getParameter("page");//核心
            if(temp == null || temp.trim().length()==0){
                temp = "1";//默认值
            }

            //调用业务层
            ArticleService articleService = new ArticleService();
            Page page = articleService.show(keywords,Integer.parseInt(temp));

            //构造Map对象
            Map<String,Object> map = new LinkedHashMap<String,Object>();
            map.put("total",page.getAllRecordNO());
            map.put("rows",page.getArticleList());

            //第三方工具将Map转成JSON
            JSONArray jsonArray = JSONArray.fromObject(map);
            String jsonJAVA = jsonArray.toString();

            //去掉二边的[]符号
            jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1);

            //以IO的流方式响应到DataGrid组件
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(jsonJAVA);
            pw.flush();
            pw.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
package loaderman.fy.dao;

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

import loaderman.fy.entity.Article;
import loaderman.util.LuceneUtil;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;

/**
 * 持久层 

 */
public class ArticleDao {
    /**
     * 根据关键字,获取总记录数
     * @return 总记录数
     */
    public int getAllRecord(String keywords) throws Exception{
        QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(),"content",LuceneUtil.getAnalyzer());
        Query query = queryParser.parse(keywords);
        IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
        TopDocs topDocs = indexSearcher.search(query,2);
        //返回符合条件的真实总记录数,不受2的影响
        return topDocs.totalHits;
        //返回符合条件的总记录数,受2的影响
        //return topDocs.scoreDocs.length;
    }
    /**
     * 根据关键字,批量查询记录
     * @param start 从第几条记录的索引号开始查询,索引号从0开始
     * @param size  最多查询几条记录,不满足最多数目时,以实际为准
     * @return 集合
     */
    public List<Article> findAll(String keywords,int start,int size) throws Exception{
        List<Article> articleList = new ArrayList<Article>();

        QueryParser queryParser = new QueryParser(LuceneUtil.getVersion(),"content",LuceneUtil.getAnalyzer());
        Query query = queryParser.parse(keywords);
        IndexSearcher indexSearcher = new IndexSearcher(LuceneUtil.getDirectory());
        TopDocs topDocs = indexSearcher.search(query,100);
        //小技巧
        int middle = Math.min(start+size,topDocs.totalHits);
        for(int i=start;i<middle;i++){
            ScoreDoc scoreDoc = topDocs.scoreDocs[i];
            int no = scoreDoc.doc;
            Document document = indexSearcher.doc(no);
            Article article = (Article) LuceneUtil.document2javabean(document,Article.class);
            articleList.add(article);
        }

        return articleList;
    }





    public static void main(String[] args) throws Exception{
        ArticleDao dao = new ArticleDao();
        System.out.println(dao.getAllRecord("培训"));

        System.out.println("------------------------------");

        System.out.println("第一页");
        List<Article> list = dao.findAll("培训",0,2);
        for(Article a : list){
            System.out.println(a);
        }
        System.out.println("第二页");
        list = dao.findAll("培训",2,2);
        for(Article a : list){
            System.out.println(a);
        }
        System.out.println("第三页");
        list = dao.findAll("培训",4,2);
        for(Article a : list){
            System.out.println(a);
        }
        System.out.println("第四页");
        list = dao.findAll("培训",6,2);
        for(Article a : list){
            System.out.println(a);
        }
    }
}
package loaderman.fy.entity;

/**
 * 文章
 */
public class Article {
    private Integer id;//编号
    private String title;//标题
    private String content;//内容
    public Article(){}
    public Article(Integer id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    @Override
    public String toString() {
        return "编号:" + id+"\n标题:" + title + "\n内容:" + content;
    }
}
package loaderman.fy.entity;

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

/**
 * 用于Article的分页类
 */
public class Page {
    private Integer currPageNO;//当前页号OK
    private Integer perPageSize = 2;//每页显示记录数,默认为2条OK
    private Integer allRecordNO;//总记录数OK
    private Integer allPageNO;//总页数OK
    private List<Article> articleList = new ArrayList<Article>();//内容OK
    public Page(){}
    public Integer getCurrPageNO() {
        return currPageNO;
    }
    public void setCurrPageNO(Integer currPageNO) {
        this.currPageNO = currPageNO;
    }
    public Integer getPerPageSize() {
        return perPageSize;
    }
    public void setPerPageSize(Integer perPageSize) {
        this.perPageSize = perPageSize;
    }
    public Integer getAllRecordNO() {
        return allRecordNO;
    }
    public void setAllRecordNO(Integer allRecordNO) {
        this.allRecordNO = allRecordNO;
    }
    public Integer getAllPageNO() {
        return allPageNO;
    }
    public void setAllPageNO(Integer allPageNO) {
        this.allPageNO = allPageNO;
    }
    public List<Article> getArticleList() {
        return articleList;
    }
    public void setArticleList(List<Article> articleList) {
        this.articleList = articleList;
    }
}
package loaderman.fy.service;

import loaderman.fy.dao.ArticleDao;
import loaderman.fy.entity.Article;
import loaderman.fy.entity.Page;

import java.util.List;

/**
 * 业务层
 */
public class ArticleService {
    //持久层
    private ArticleDao articleDao = new ArticleDao();
    /**
     * 根据关键字和页号,查询内容
     */
    public Page show(String keywords,int currPageNO) throws Exception{
        Page page = new Page();

        //封装当前页号
        page.setCurrPageNO(currPageNO);

        //封装总记录数
        int allRecordNO = articleDao.getAllRecord(keywords);
        page.setAllRecordNO(allRecordNO);

        //封装总页数
        int allPageNO = 0;
        if(page.getAllRecordNO() % page.getPerPageSize() == 0){
            allPageNO = page.getAllRecordNO() / page.getPerPageSize();
        }else{
            allPageNO = page.getAllRecordNO() / page.getPerPageSize() + 1;
        }
        page.setAllPageNO(allPageNO);

        //封装内容
        int size = page.getPerPageSize();
        int start = (page.getCurrPageNO()-1) * size;
        List<Article> articleList = articleDao.findAll(keywords,start,size);
        page.setArticleList(articleList);

        return page;
    }







    //测试
    public static void main(String[] args) throws Exception{
        ArticleService test = new ArticleService();
        Page page = test.show("培训",4);

        System.out.println(page.getCurrPageNO());
        System.out.println(page.getPerPageSize());
        System.out.println(page.getAllRecordNO());
        System.out.println(page.getAllPageNO());
        for(Article a : page.getArticleList()){
            System.out.println(a);
        }
    }
}
<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>使用Jsp +Js + Jquery + EasyUI + Servlet + Lucene,完成分页</title>
    <!-- 引入css文件,无顺序 -->
    <link rel="stylesheet" href="themes/icon.css" type="text/css"></link>
    <link rel="stylesheet" href="themes/default/easyui.css" type="text/css"></link>
      <!-- 引入js文件,有顺序 -->
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="js/easyui-lang-zh_CN.js"></script>
  </head>
  <body>


    <!-- 输入区 -->
    <form id="myformID">
        输入关键字:<input type="text" value="" id="keywordID"/>
        <input type="button" value="站内搜索" id="findID"/>
    </form>
    <script type="text/javascript">
        //定位"站内搜索"按钮
        $("#findID").click(function(){
            //获取关键字
            var keyword = $("#keywordID").val();
            //去空格
            keyword = $.trim(keyword);
            //判断
            if(keyword.length == 0){
                //提示
                alert("请输入关键字!!!");
                //清空文本框的内容
                $("#keywordID").val("");
                //定位于输入关键字文本框
                $("#keywordID").focus();
            }else{
                //异步发送请求到服务器
                //load表示方法名
                //"keywords"表示需要发送的的参数名,后台收:request.getParameter("keywords")
                //keyword表示参数值
                $("#dg").datagrid("load",{    
                    "keywords" : keyword
                });  
            }
        });
    </script>
    
    

    <!-- 显示区 -->
    <table id="dg"></table>
    <script type="text/javascript">
        $("#dg").datagrid({
            url : "${pageContext.request.contextPath}/ArticleServlet?time="+new Date().getTime(),
            columns :  [[    
                                {field:id,title:编号,width:100},    
                                {field:title,title:标题,width:100},    
                                {field:content,title:内容,width:100}
                        ]],
            fitColumns : true,
            singleSelect : true,
            pagination : true,
            pageSize : 2,
            pageList : [2]            
        });
    </script>
    
  </body>
</html>

 

Jsp +Js + Jquery + EasyUI + Servlet + Lucene,完成分页

标签:time()   去掉   click   显示   encoding   style   override   opd   input   

原文地址:https://www.cnblogs.com/loaderman/p/10059983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!