热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

基于Lucene的搜索系统同时使用Paoding进行中文分词二

在基于Lucene的搜索系统同时使用Paoding进行中文分词一中讲解了利用lucene建立索引的过程以及对搜索条件,和结果封装,今天来看客户端是怎么调用透露给外部的servlet

在基于Lucene的搜索系统 同时使用Paoding进行中文分词 一 中讲解了利用lucene建立索引的过程以及对搜索条件,和结果封装,今天来看客户端是怎么调用透露给外部的servlet的

《基于Lucene的搜索系统 同时使用Paoding进行中文分词 二》

项目结构如上图

其中search报下的

《基于Lucene的搜索系统 同时使用Paoding进行中文分词 二》

这几个类就不做说明了 ,可以在基于Lucene的搜索系统 同时使用Paoding进行中文分词 一 找到

上代码:

LIstGood.java

package com.ajun.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ajun.search.SearchResultInfo;
import com.ajun.utils.SearchUtil;
/**
*
* @author ajun
*
*/
public class ListGood extends HttpServlet {
/**
* The doGet method of the servlet.

*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet.

*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String cOndition= request.getParameter("condition");//接受页面传递过来的条件参数此时已经瓶装好了,如果不想拼装还可以单独接受
if(condition!=null){
cOndition= new String(condition.getBytes("ISO-8859-1"),"UTF-8");
}
SearchResultInfo restule = SearchUtil.getResultObjectFromJson(condition);//返回封装好搜索结果对象
request.setAttribute("result", restule);
request.setAttribute("condition", condition);
request.getRequestDispatcher("/index.jsp").forward(request, response);

}
}

HttpTool.java

package com.ajun.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
/**
* Http操作辅助工具
* @author ajun
*
*/
public class HttpTool {
/**
* GET请求数据
* @param get_url url地址
* @param content key=value形式
* @return 返回结果
* @throws Exception
*/
public String sendGetData(String get_url, String content) throws Exception {
String result = "";
URL getUrl = null;
BufferedReader reader = null;
String lines = "";
HttpURLConnection cOnnection= null;
try {
if (content != null && !content.equals(""))
get_url = get_url + "?" + content;
//get_url = get_url + "?" + URLEncoder.encode(content, "utf-8");
getUrl = new URL(get_url);
cOnnection= (HttpURLConnection) getUrl.openConnection();
connection.connect();
// 取得输入流,并使用Reader读取
reader = new BufferedReader(new InputStreamReader(connection
.getInputStream(), "utf-8"));// 设置编码
while ((lines = reader.readLine()) != null) {
result = result + lines;
}
return result;
} catch (Exception e) {
throw e;
} finally {
if (reader != null) {
reader.close();
reader = null;
}
connection.disconnect();
}
}
/**
* @param POST_URL url地址
* @param content key=value形式
* @return 返回结果
* @throws Exception
*/
public String sendPostData(String POST_URL, String content)
throws Exception {
HttpURLConnection cOnnection=null;
DataOutputStream out=null;
BufferedReader reader=null;
String line = "";
String result="";
try {
URL postUrl = new URL(POST_URL);
cOnnection= (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
// Post 请求不能使用缓存
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();

out = new DataOutputStream(connection.getOutputStream());
//cOntent= URLEncoder.encode(content, "utf-8");
// DataOutputStream.writeBytes将字符串中的16位的unicode字符?8位的字符形式写道流里?
out.writeBytes(content);
out.flush();
out.close();
//获取结果
reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));// 设置编码
while ((line = reader.readLine()) != null) {
result=result+line;
}
return result;
} catch (Exception e) {
throw e;
}finally
{
if(out!=null)
{
out.close();
out=null;
}
if(reader!=null)
{
reader.close();
reader=null;
}
connection.disconnect();
}
}
/*
* 过滤掉html里不安全的标签,不允许用户输入这些标?
*/
public static String htmlFilter(String inputString) {
//return inputString;
String htmlStr = inputString; // 含html标签的字符串
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;


try {
String regEx_script = "<[\\s]*?(script|style)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(script|style)[\\s]*?>";
String regEx_Onevent="on[^\\s]+=\\s*";
String regEx_hrefjs="href=Javascript:";
String regEx_iframe="<[\\s]*?(iframe|frameset)[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?(iframe|frameset)[\\s]*?>";
String regEx_link="<[\\s]*?link[^>]*?/>";

htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr=Pattern.compile(regEx_onevent, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr=Pattern.compile(regEx_hrefjs, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr=Pattern.compile(regEx_iframe, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr=Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");

//p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
// m_html = p_html.matcher(htmlStr);
// htmlStr = m_html.replaceAll(""); // 过滤html标签
textStr = htmlStr;
} catch (Exception e) {
System.err.println("Html2Text: " + e.getMessage());
}
return textStr;
}
}

SearchUtil.java

package com.ajun.utils;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import com.ajun.search.ConditionInfo;
import com.ajun.search.ConditionMethod;
import com.ajun.search.SearchItemInfo;
import com.ajun.search.SearchResultInfo;
/**
*
* @author ajun
*
*/
public class SearchUtil {
/**
* 返回结果集合
* @param condition 条件对象
* @return
*/
public static SearchResultInfo getResultObjectFromJson(ConditionInfo condition){
SearchResultInfo sr = null;
try {
String urlParams = ConditionMethod.getConditionUrl(condition);
String url = PubConstant.getValue("searchUrl")+urlParams;
String cOntent= new HttpTool().sendGetData(url, "");
JSONObject json = JSONObject.fromObject(content);
if(json!=null){
Map map = new HashMap();
map.put("itemLists", SearchItemInfo.class);
sr = (SearchResultInfo)JSONObject.toBean(json,SearchResultInfo.class,map);
}
System.out.println(json);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return sr;
}

public static SearchResultInfo getResultObjectFromJson(String conditionUrl){
SearchResultInfo sr = null;
try {
String url = PubConstant.getValue("searchUrl")+conditionUrl;
if(cOnditionUrl==null || "".equals(conditionUrl.trim())){
ConditionInfo c = new ConditionInfo();
url = ConditionMethod.getConditionUrl(c);
}
String cOntent= new HttpTool().sendGetData(url, "");
JSONObject json = JSONObject.fromObject(content);
if(json!=null){
Map map = new HashMap();
map.put("itemLists", SearchItemInfo.class);
sr = (SearchResultInfo)JSONObject.toBean(json,SearchResultInfo.class,map);
}
System.out.println(json);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return sr;
}
}

PubConstant.java

package com.ajun.utils;
import java.io.IOException;
import java.util.Properties;
/*
* @author ajun
* @date 2011-07-31
*/
public class PubConstant {
private static Properties properties= new Properties();
static{
try {
properties.load(PubConstant.class.getClassLoader().getResourceAsStream("constant.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getValue(String key){
String value = (String)properties.get(key);
return value.trim();
}
}

 constant.properties

mysql_Url=jdbc\:mysql\://127.0.0.1/goodsearch?useUnicode\=true&characterEncoding\=UTF-8
mysql_UserName=xxxxx
mysql_Password=xxxx
searchUrl=http\://127.0.0.1\:8080/searcher/getResult?condition\=

goodsearch.js用于条件对象和条件字符串的转换

/**
*条件对象
* **/
function conditionInfo(){
this.keyWords='',
this.withoutWords='',
this.goodId='',
this.minPrice='',
this.maxPrice='',
this.orderbyName='uptime',
this.orderbyValue='desc',
this.pageSize='20',
this.pageIndex='1'
}


/**
* 将action传递过来的condition字符串转换为conditionInfo js 对象
* */
function StrToConditionInfoObject(url){
var urlStr =url;
var obj = new conditionInfo();
if(urlStr!=''){
var urls = urlStr.split('-',100);
obj.keyWords=urls[0];
obj.withoutWords=urls[1];
obj.goodId=urls[2];
obj.minPrice=urls[3];
obj.maxPrice=urls[4];
obj.orderbyName=urls[5];
obj.orderbyValue=urls[6];
obj.pageSize=urls[7];
obj.pageIndex=urls[8];
}

return obj;
}

/**
* 条件对象转换为Url地址
* param condition 条件对象
* */
function createUrl(condition){
var con = '';
var lastcOnInfo='';
for(var index in condition){
if(condition[index]==null || condition[index]==''){
con+=''+'-';
}else{
con+=condition[index]+'-';
}
}
if(con!=''){
lastcOnInfo= con.substring(0,con.length-1);
}
return lastconInfo;
//return encodeURI(lastconInfo);
}

/**
* 搜索商品列表
* @param {Object} conditionInfo 条件对象
* @param {Object} action 提交url
*/
function searchByCondition(conditionInfo,action){
var url = createUrl(conditionInfo);
//alert(url);
document.location.href=action+'?cOndition='+url;
}

index.jsp搜索页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


































GoodName:

minPrice:

maxPrice:


IdNamePriceUptime
${item.id }${item.name }${item.price }2010-09-09



效果如下:

《基于Lucene的搜索系统 同时使用Paoding进行中文分词 二》

大家可以不用goodsearch.js

条件参数可以直接传递到后台 ,然后在后台接受 ,set到ConditionInfo对象就可以了

源码可以在我的资源中进行下载


推荐阅读
author-avatar
看人不顺眼说明6自己没教养
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有