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

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

项目结构如上图

其中search报下的

这几个类就不做说明了 ,可以在基于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. <br>
	 *
	 * 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. <br>
	 *
	 * 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<String,Class> map = new HashMap<String,Class>();
				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<String,Class> map = new HashMap<String,Class>();
				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+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	 <script type="text/javascript" src="script/jquery.min.js"></script>
	 <script type="text/javascript" src="script/goodsearch.js"></script>
	 <script type="text/javascript">
	 	function search(){
	 		var condition = StrToConditionInfoObject('${condition}');
	 		if($.trim($('#keyWords').val())!=''){
	 			condition.keyWords = $('#keyWords').val();
	 			
	 		}else{
	 			condition.keyWords='';
	 		}
	 		if($.trim($('#minPrice').val())!=''){
	 			condition.minPrice = $('#minPrice').val();
	 			
	 		}else{
	 			condition.minPrice='0';
	 		}
	 		if($.trim($('#maxPrice').val())!=''){
	 			condition.maxPrice = $('#maxPrice').val();
	 			
	 		}else{
	 			condition.maxPrice='';
	 		}
	 		//condition.minPrice = '10.00';
	 		searchByCondition(condition,'ListGood');
	 	}
	 </script>
  </head>
  
  <body>
    <table border="1">
    	<tr>
    		<td colspan="4">
    			GoodName:<input id="keyWords" value="" type="text"/><br/>
    			minPrice:<input id="minPrice" value="" type="text"/><br/>
    			maxPrice:<input id="maxPrice" value="" type="text"/><br/>
    			<input id="keyWords" value="Search" type="button" οnclick="search();"/>
    		</td>
    	</tr>
    	<tr>
    		<td>Id</td>
    		<td>Name</td>
    		<td>Price</td>
    		<td>Uptime</td>
    	</tr>
    	<c:forEach items="${result.itemLists}" var="item">
    		<tr>
	    		<td>${item.id }</td>
	    		<td>${item.name }</td>
	    		<td>${item.price }</td>
	    		<td>2010-09-09</td>
	    	</tr>
    	</c:forEach>
    </table>
  </body>
</html>

效果如下:

大家可以不用goodsearch.js

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


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


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飓风zj

感谢打赏,thanks

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值