flex中的restrict详解

除 .$ ^ { [ ( | ) * +   \ 外,其他字符与自身匹配。
但是其中并未注明这些字符应该匹配为什么字符。
为了方便自己以后查阅,也为了方便网友搜索我就写在这里了。
[Sipo]
点的转义:.  ==> \\u002E
美元符号的转义:$  ==> \\u0024
乘方符号的转义:^  ==> \\u005E
左大括号的转义:{  ==> \\u007B
左方括号的转义:[  ==> \\u005B
左圆括号的转义:(  ==> \\u0028
竖线的转义:| ==> \\u007C
右圆括号的转义:) ==> \\u0029
星号的转义:*  ==> \\u002A
加号的转义:+  ==> \\u002B
问号的转义:   ==> \\u003F
反斜杠的转义:\ ==> \\u005C

 

 

Flex当中大家都知道有些标签restrict,这个属性用处很大的。对一些正则表达式都使用,跟以前的javascript是一样的。

 

下面是我封装FLex当中的textInput的restrict:

 

package common
{
 import mx.controls.TextInput;

 public class textInputRscdCode extends TextInput
 {
  public function textInputRscdCode()
  {
      this.restrict=”0-9 a-z A-Z ~ ! # %  \\^ & \\* ( ) \\- _ = + \\\\ | , . < > /   “;
   super();
  }
 }
}

 

表明在页面的输入框中只能让它输入这些东西。其他的不行。

 

 

 

 

<!—-><!—-><!—->

LiveSearch[RailsRecipes]

类似于自动完成的功能。

下面开始Coding 

建立我们的数据库

def self.up
  create_table "recipes" do |t|
    t.column "name", :string
    t.column "region", :string
    t.column "instructions", :text
  end
  create_table "ingredients" do |t|
    t.column "recipe_id", :integer
    t.column "name", :string
    t.column "unit", :string
    t.column "quantity", :integer
  end
end

建立我们的Controller, 建立search code

app> script/generate controller Search
   exists app/controllers/
   exists app/helpers/
   create app/views/search
   exists test/functional/
   create app/controllers/search_controller.rb
   create test/functional/search_controller_test.rb
   create app/helpers/search_helper.rb

当然了,还要有一个view

<html>
  <head>
    <%= javascript_include_tag :defaults %>
  </head>
  <body>
    <%= text_field_with_auto_complete :recipe, :name %>
  </body>
</html>

像以前一样,加上<%= javascript_include_tag :defaults %>

然后<%= text_field_with_auto_complete :recipe, :name %>这句就会显示出魔法效果。

然后在controller里

class SearchController < ApplicationController
  auto_complete_for :recipe, :name
end

jQuery支持的方法

字符串,数组和对象相关的工具方法

<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>字符串,数组和对象相关的工具方法</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">
	<script type="text/javascript" src="js/jquery-1.4.3.js"></script>
  </head>
  
  <body>
		<script type="text/javascript">
			//访问浏览器属性
			for ( var key in $.browser) {
				document.writeln("当前浏览器的" + key + "属性为:" + $.browser[key] + "<br />");
			}
			//去除字符串前后的空白
			document.writeln("$.trim('	ddd'));的结果是" + $.trim("	ddd") + "<br />");
			//遍历数组
			$.each( [ "java", "ajax", "java ee" ], function(index, val) {
				document.writeln("['java' , 'ajax' ,'java ee']的第" + index + "个元素为:"
						+ val + "<br />");
			});
			//以指定函数过滤数组
			var grepResult = $.grep( [ "java", "ajax", "java ee" ],
					function(val, index) {
						//当数组元素的字符个数大于5时被保留
					return val.length > 5;
				});
			document.writeln("['java' , 'ajax' ,'java ee']里数组元素的字符个数大于5的还有:"
					+ grepResult + "<br />");
			//以旧数组创建新数组
			var mapResult = $.map( [ "java", "ajax", "java ee" ], function(val, index) {
				//当数组元素和索引值连缀在一起作为新的数组元素
					return val + index
				});
			document.writeln("以['java' , 'ajax' ,'java ee']创建的新数组为:" + mapResult);
			//创建div元素
			var div = $("<div>aa<div>");
			//以相同的两个div创建数组
			var divArr = [ div, div ];
			document.writeln("divArr.length的值为:" + divArr.length + "<br />");
			//执行$.unique去除重复元素
			document.writeln("$.unique(divArr).length的结果为:" + $.unique(divArr).length
					+ "<br />");
			var str = "aa";
			//以两个相同的字符串创建数组
			var strArr = [ str, str ];
			document.writeln("strArr.length的值为:" + strArr.length + "<br />");
			//执行$.unique不能去除重复元素
			document.writeln("$.unique(strArr).length的结果为:" + $.unique(strArr).length
					+ "<br />");
		</script>
	</body>
</html>

 数据存储的相关方法

<body>
		<script type="text/javascript">
			var target = $("<div>java</div>");
			//向jQuery对象里添加book数据
			target.data("book" , "Java");
			//访问jQuery对象里的book数据,将输出"Java"
			alert(target.data("book"));
			//删除jQuery对象里的book数据
			target.removeData("book");
			//再次访问jQuery对象里的book数据,将输出"undefined"
			alert(target.data("book"));
		</script>
</body>

 操作属性的相关方法

<body>
		<img />
		<img />
		<div>
			<img />
			<img />
			<img />
		</div>
		<script type="text/javascript">
			//获取body下的img元素,并为这些img元素设置src属性值
			$("body>img").attr("src", "logo.jpg").attr("alt", "Java");
			//获取div下的img元素,并为这些img元素设置src属性值
			$("div>img").attr("src", function(index) {
				return index + 1 + ".gif";
			});
		</script>
	</body>

 操作CSS属性的相关方法

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<base href="<%=basePath%>">

		<title>操作CSS属性的相关方法</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">
		<script type="text/javascript" src="js/jquery-1.4.3.js"></script>
		<style type="text/css">
		.test {
			background-color: #ccccff;
			border: 2px dotted red;
			font-weight: bold;
		}
		</style>
	</head>

	<body>
		<div id="test1">
			整体添加CSS样式的元素
		</div>
		<br />
		<div id="test2">
			采用css(properties)方法添加CSS样式的元素
		</div>
		<br />
		<div id="test3" style="position: absolute;">
			可以自由移动的元素
		</div>
		<script type="text/javascript">
			//为id为test1的元素设置class="text"
			$("#test1").addClass("test");
			//为id为test2的元素设置内联CSS样式 , css(properties), properties是一个形如{key:value}的对象
			$("#test2").css( {
				border : "1px solid black",
				color : "#888888"
			});
			//获取id为test3的元素
			var target = $("#test3")
			//设置背景色
					.css("background-color", "#cccccc").css("padding", 10)
					//设置宽度
					.width(200)
					//设置高度
					.height(80)
					//设置位置
					.css("left", 100).css("top", 164);
			//获取target的位置
			var posi = target.position();
			alert("target的X座标为:" + posi.left + "\n" + "target的Y座标为:" + posi.top);
		</script>
	</body>
</html>

 操作HTML元素内容的相关属性

<body>
		<div></div>
		<div></div>
		<input id="book" name="book" type="text" />
		<br />
		<input id="desc" name="desc" type="text" />
		<br />
		<select id="gender">
			<option value="male">
				男人
			</option>
			<option value="female">
				女人
			</option>
		</select>
		<br />
		<select id="publish" multiple="multiple">
			<option value="phei">
				电子工业出版社
			</option>
			<option value="tsinghua">
				清华大学出版社
			</option>
		</select>
		<br />
		<script type="text/javascript">
			//设置body下的div元素的内容
			$("body>div").html("Ajax");
			//设置所有input、select和textarea的值
			$("body>input").val("XML");
			//为所有的<select.../>元素设置value值
			$("select").val( [ "female", "tsinghua"]);
			//仅获取jQuery元素的text部分,下面将输出java:Java
			alert($("<div>java:<span>Java</span></div>").text());
		</script>
	</body>

 操作DOM节点的相关方法

<body>
		<div id="test1"></div>
		<div id="test2" style="border: 1px solid black;">
			id为test2的元素
		</div>
		<script type="text/javascript">
			//直接将一段HTML字符串添加到id为test1的元素的内部的尾端
			$("#test1").append("<b>XML</b>");
			//创建一个<span.../>元素
			var span = document.createElement("span");
			span.innerHTML = "Java"
			//将一个DOM元素添加到id为test1的元素的内部的顶端
			$("#test1").prepend(span);
			//将id为test1的元素添加到id为test2的元素内部的尾端
			$("#test1").appendTo("#test2");
		</script>
	</body>

 操作DOM节点的相关方法(在指定的节点添加节点)

<body>
		<div id="test1" style="border: 1px dotted black;">
			id为test1的元素
		</div>
		<br />
		<div id="test2" style="border: 1px solid black;">
			id为test2的元素
		</div>
		<hr />
		<script type="text/javascript">
			//直接将一段HTML字符串插入到id为test1的元素的的前面
			$("#test1").before("<b>Ajax</b>");
			//直接将一段HTML字符串插入到id为test1的元素的的后面
			$("#test1").after("<b>XML</b>");
			//将id为test2的元素插入hr元素之后
			$("#test2").insertAfter("hr");
		</script>
	</body>

 操作DOM节点的相关方法(包裹DOM节点)

<body>
		<span id="test1">id为test1的元素</span>
		<br />
		<span id="test2">id为test2的元素</span>
		<script type="text/javascript">
		//将每个span元素之外再包裹一个带点线边框的div元素
		$("span").wrap("<div style='border:1px dotted black'></div>");
		//将每个span元素内部成分再包裹一个灰色背景的span元素
		$("span").wrapInner("<span style='background-color:#dddddd'></span>");
		</script>
	</body>

 操作DOM节点的相关方法(替换,删除,复制)

<body>
		<div>
			<span id="test1">id为test1的元素</span>Java
		</div>
		<span id="test2">id为test2的元素</span>
		<script type="text/javascript">
			//将div元素内容全部清空
			$("div").empty()
			//重新添加字符串
					.append("重新添加");
			//删除所有id为test2的span元素
			$("span").remove("#test2");
			//取得页面中div元素,并复制该元素
			$("div").clone()
			//添加背景色
					.css("background-color", "#cdcdcd")
					//添加到body元素尾部
					.appendTo("body");
		</script>
	</body>

 

Javascript解析josn数据

1.简单的JS解析JOSN串的例子   

2.  var obj = {name:’cat’,color:’black’};   

3.  这是JS定义一个对象,obj.name值为cat,obj.color值为black   

4.  如果我们要从服务器获返回一个这样的字串data = “{name:’cat’,color:’black’}”   

5.  var obj = eval(“(“+data+”)”);   

6.  那么得到的obj.name值也是’cat’,obj.color值是’balck’,这样就OK了!

如果是从后台返回的数据的话,最后设置下返回数据类型为josn这样在前台就不需要在转换一下了,可以直接拿来用的!

设置网页刷新

http-equiv=”refresh” 

admin管理界面的urls的生成

 

为了可以在django应用中使用admin管理界面,可以在urls.py中增加以下一些代码:

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

...
urlpatterns = patterns('',
    ...  
    # Uncomment the next line to enable the admin:
    (r'^admin/', include(admin.site.urls)),
    ...
)

 

 

下面来分析一下admin对应的urls是如何引用的。

首先来看autodiscover()

源码位于django\contrib\admin\__init__.py中:

def autodiscover():
    ...
    for app in settings.INSTALLED_APPS:
        mod = import_module(app)
        # Attempt to import the app's admin module.
        try:
            before_import_registry = copy.copy(site._registry)
            import_module('%s.admin' % app)
        except:
            site._registry = before_import_registry

 

这个函数将settings.INSTALLED_APPS列表中的app进行注册或导入相关模块,如admin有关的进行注册,以后可以使用site._registry来进行引用。(此处不包含model的注册)

 

真正产生urls的是(r’^admin/’, include(admin.site.urls))。

admin.site是在django\contrib\sites.py中的最后一行生成的。

site = AdminSite()

所以admin.site.urls实际上是类AdminSite的属性。

    def urls(self):
        return self.get_urls(), self.app_name, self.name
    urls = property(urls)

 

从上面的代码看生成的关键在于类AdminSite的方法get_urls()中

    def get_urls(self):
        ...
        # Admin-site-wide views.(Admin-site范围的视图)
        urlpatterns = patterns('',
            url(r'^$',
                wrap(self.index),
                name='index'),
            url(r'^logout/$',
                wrap(self.logout),
                name='logout'),
            url(r'^password_change/$',
                wrap(self.password_change, cacheable=True),
                name='password_change'),
            url(r'^password_change/done/$',
                wrap(self.password_change_done, cacheable=True),
                name='password_change_done'),
            url(r'^jsi18n/$',
                wrap(self.i18n_javascript, cacheable=True),
                name='jsi18n'),
            url(r'^r/( P<content_type_id>\d+)/( P<object_id>.+)/$',
                'django.views.defaults.shortcut'),
            url(r'^( P<app_label>\w+)/$',
                wrap(self.app_index),
                name='app_list')
        )

        # Add in each model's views.(增加每个model的视图)
        for model, model_admin in self._registry.iteritems():
            urlpatterns += patterns('',
                url(r'^%s/%s/' % (model._meta.app_label, model._meta.module_name),
                    include(model_admin.urls))
            )
        return urlpatterns

 

 

对于每个model的url是通过include(model_admin.urls)来进行加入的.而每个model是使用admin.site.register(model_name,modelAdmin)等形式来注册的.下面来查看AdminSite的register函数:

    def register(self, model_or_iterable, admin_class=None, **options):
 	...
        for model in model_or_iterable:
	    ...
            if options:
                # For reasons I don't quite understand, without a __module__
                # the created class appears to "live" in the wrong place,
                # which causes issues later on.
                options['__module__'] = __name__
                admin_class = type("%sAdmin" % model.__name__, (admin_class,), options)
	    ...
            # Instantiate the admin class to save in the registry
            self._registry[model] = admin_class(model, self)

 

可以看出get_urls()中model_admin应该是类ModelAdmin的实例.所有model_admin.urls实际上是类ModelAdmin的属性,具体的与admin-site视图的urls处理类似了.

    def get_urls(self):
        ...
        urlpatterns = patterns('',
            url(r'^$',
                wrap(self.changelist_view),
                name='%s_%s_changelist' % info),
            url(r'^add/$',
                wrap(self.add_view),
                name='%s_%s_add' % info),
            url(r'^(.+)/history/$',
                wrap(self.history_view),
                name='%s_%s_history' % info),
            url(r'^(.+)/delete/$',
                wrap(self.delete_view),
                name='%s_%s_delete' % info),
            url(r'^(.+)/$',
                wrap(self.change_view),
                name='%s_%s_change' % info),
            )
        return urlpatterns

    def urls(self):
        return self.get_urls()
    urls = property(urls)

 

 

javascript页面跳转

    <script type=”text/javascript” language=”javascript”>
        var i=5;
        var Intervalid;
        Intervalid = setInterval(“fun()”,1000);//取出Interval函数的返回值
        function fun()
        {
            if(i==0)
            {
                window.location.href=”Default.aspx”;
                clearInterval(Intervalid);//清除参数,这样就不会出现负数
            }
            document.getElementById(“aa”).innerHTML=i;
            i–;
        }
    </script>

SomearrangementonDOM

I have seen a good introducing article about Dom(Document Object Model):

The purpose of this assignment was to learn how to use
JavaScript with the DOM(Document Object Model),
and about some of the properties
available through the DOM’s window object.

The description and my solution of the
DOM Properties-assignment can be viewed
at the bottom of this page.

What is DOM

The DOM is an API for HTML and XML documents.

It defines the structure of documents and the way to access that structure in favor for manipulating how the document will be presented, what the document’s content will be and how the document will be structured.

With this model programmers can create documents, navigate the document, add, change or delete elements and content.

A very common script language using DOM as a model is JavaScript. However, the model itself has noting to do with JavaScript, it is simply a model that can be used by any programming language or scripting language.

Care must be taken when using the DOM since many browsing software offer extensions not following the W3C standard.

What is the DOM Window Object 

The window object represents the window itself. It is created automatically with every instance of a <body> or <frameset> tag. The window object contains the document as a child and provides – among others objects – access to the useful window.navigator and window.screen objects. These two objects are often used for manipulating the browsing environment itself, and provides many special properties for accessing objects futher down the tree structure.

Assignment Description

Create a Web page with functionality for displaying the different properties of the window, window.screen, window.navigator window.location, window.history and window.document objects.

Original Address: http://www.webpelican.com/internet-programming-3/dom-properties/

dom Structure see: http://www.howtocreate.co.uk/tutorials/javascript/domstructure

Basic object model for all modern browsers:

window

|

————————————————————————–

| | | | |

navigator screen document history location

About typeof:

typeof
returns one of the following strings
:

  • number
  • string
  • boolean
  • object
  • function
  • undefined (= null )
typeof(typeof(x))
is always string
, no matter what x actually is.
IE seems to think that some functions are objects rather than functions: typeof(document.getElementById)
returns object.
I have done a testing code about all the objects in DOM, it concerns all the properties of all the objects.
Here is the code:

EXT日期

问题描述,如何把后台的日期格式传到前台让Ext来解析呢 ,且不会丢失精度?

       第一步,我们先来看看Ext.util.Format的方法说明

date ( String/Date value , [String format ]  ) : String

Parse a value into a formatted date using the specified format pattern.

Parse a value into a formatted date using the specified format pattern.

Parameters:

value : String/Date

The value to format (Strings must conform to the format expected by the javascript Date object’s parse() method )

format : String

(optional) Any valid date format string (defaults to ‘m/d/Y’)

Returns:

String

The formatted date string

上面加粗的相信大家看到了 ,只要我们传回的日期格式的字符串能被javaScript 中的 Date的parse解析的话,那么在前台Ext就会自动识别

现在焦点就转移的js Date.parse的方法上了,用脑袋笨寻思就是知道,如果parse不知道GMT格式的字符串,那么他就太笨了,呵呵

所以我们日期类型在向前台返回时只要 返回  logTime.toGMTString()这个就可以了

后台  logTime.toGMTString()

前台

{

            header : “操作时间”,

            dataIndex : “logTime”,

            width : 80,

            sortable : true,

            renderer : Ext.util.Format.dateRenderer(‘Y-m-d H:i:s’)//想转成什么样的类型都可以了

        }

不需要修改任何Ext代码

datefield 组件 —- >format格式.

js常用正则表达式实例

匹配中文字符的正则表达式: [\u4e00-\u9fa5] 

匹配双字节字符(包括汉字在内):[^\x00-\xff] 

应用:计算字符串的长度(一个双字节字符长度计2,ASCII字符计1) 

String.prototype.len=function(){return this.replace([^\x00-\xff]/g,"aa").length;} 

匹配空行的正则表达式:\n[\s| ]*\r 

匹配HTML标记的正则表达式:/<(.*)>.*<\/\1>|<(.*) \/>/  

匹配首尾空格的正则表达式:(^\s*)|(\s*$) 

应用:javascript中没有像vbscript那样的trim函数,我们就可以利用这个表达式来实现,如下: 

String.prototype.trim = function() 

return this.replace(/(^\s*)|(\s*$)/g, ""); 

利用正则表达式分解和转换IP地址: 

下面是利用正则表达式匹配IP地址,并将IP地址转换成对应数值的Javascript程序: 

function IP2V(ip) 

re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正则表达式 
if(re.test(ip)) 

return RegExp.$1*Math.pow(255,3))+RegExp.$2*Math.pow(255,2))+RegExp.$3*255+RegExp.$4*1 

else 

throw new Error("Not a valid IP address!") 

不过上面的程序如果不用正则表达式,而直接用split函数来分解可能更简单,程序如下: 

var ip="10.100.20.168" 
ip=ip.split(".") 
alert("IP值是:"+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1)) 

匹配Email地址的正则表达式:\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)* 

匹配网址URL的正则表达式:http://([\w-]+\.)+[\w-]+(/[\w- ./ %&=]*)  

利用正则表达式去除字串中重复的字符的算法程序:[注:此程序不正确,原因见本贴回复] 

var s="abacabefgeeii" 
var s1=s.replace(/(.).*\1/g,"$1") 
var re=new RegExp("["+s1+"]","g") 
var s2=s.replace(re,"")  
alert(s1+s2) //结果为:abcefgi 

这个方法对于字符顺序有要求的字符串可能不适用。 

得用正则表达式从URL地址中提取文件名的javascript程序,如下结果为page1 

s="http://www.9499.net/page1.htm" 
s=s.replace(/(.*\/){0,}([^\.]+).*/ig,"$2") 
alert(s) 

利用正则表达式限制网页表单里的文本框输入内容: 


正则表达式限制只能输入中文:onkeyup="value="/value.replace(/["^\u4E00-\u9FA5]
/g,’’)" onbeforepaste="clipboardData.setData(’text’,clipboardData.getData(’text’).replace(/[^\u4E00-\u9FA5]/g,’’))" 

用正则表达式限制只能输入全角字符: onkeyup="value="/value.replace(/["^\uFF00-
\uFFFF]/g,’’)" onbeforepaste="clipboardData.setData(’text’,clipboardData.getData(’text’).replace(/[^\uFF00-\uFFFF]/g,’’))" 

用正则表达式限制只能输入数字:onkeyup="value="/value.replace(/["^\d]
/g,’’) "onbeforepaste="clipboardData.setData(’text’,clipboardData.getData(’text’).replace(/[^\d]/g,’’))" 

用正则表达式限制只能输入数字和英文:onkeyup="value="/value.replace(/[\W]
/g,"’’) "onbeforepaste="clipboardData.setData(’text’,clipboardData.getData(’text’).replace(/[^\d]/g,’’))"

Lucene全文检索中用到方法

Services中调用接口方法:

   1.重新生成索引

      

 /**
     * 重新生成索引
     *
     * @return
     */
    public String newIndex(String page) {
        HelpSearchDomain helpSearchDomain = (HelpSearchDomain) getContextBean("helpSearchDomain");
        BaseInfoAttributeDomain baseInfoAttributeDomain = (BaseInfoAttributeDomain) getContextBean("baseInfoAttributeDomain");
        //设置分页对象信息
        SplitPage sp = new SplitPage();
        sp.setCurrentPage(Integer.parseInt(page));
        sp.setPageSize(20);
        List knowledgeList = baseInfoAttributeDomain.getAllBaseInfoAttribute("1", sp);
        String path = "D:\\upload";
        path = PropertiesUtil.get("PATH", path);
        if (knowledgeList != null && knowledgeList.size() > 0) {
            for (Iterator iterator = knowledgeList.iterator(); iterator.hasNext();) {
                BaseInfoAttribute bi = (BaseInfoAttribute) iterator.next();
                BaseInfoAttribute bia = null;
                System.out.println(bi.getInfoType().getType());
                if (bi.getInfoType().getType().equals(InfoType.ZSK)) {
                    bia = baseInfoAttributeDomain.findBaseInfoAttribute(bi.getId());
                }
                try {
                    helpSearchDomain.delKnowledgeIndex(path + "\\" + bia.getContent(), bia.getInfoType().getName(), path);//删除索引
                } catch (Exception e) {
                    e.getMessage();
                }
            }
            for (Iterator iterator = knowledgeList.iterator(); iterator.hasNext();) {
                BaseInfoAttribute bi = (BaseInfoAttribute) iterator.next();
                if (bi.getInfoType().getType().equals(InfoType.ZSK)) {
                    BaseInfoAttribute bia = baseInfoAttributeDomain.findBaseInfoAttribute(bi.getId());
                    helpSearchDomain.createKnowledgeIndex(false, path + "\\" + bia.getContent(), path, bia.getTitle(), bia.getCreatetime(), bia.getInfoType().getName(), String.valueOf(bi.getId()));
                }
            }
        }
        return "索引生成成功";
    }

 

2.根据条件检索内容

  

/**
     * 根据条件检索内容
     *
     * @param keyword
     * @param type
     * @param page
     * @return
     */
    public Object searchKnowledgeQuery(String keyword, String type, String page) {
        HelpSearchDomain helpSearchDomain = (HelpSearchDomain) getContextBean("helpSearchDomain");
        String path = "D:\\upload";
        SplitPage sp = new SplitPage();
        sp.setPageSize(18);
        sp.setCurrentPage(page == null   1 : Integer.parseInt(page));
        String isExist = helpSearchDomain.isExistsKnowlegeIndex(path);
        List returnlist = new ArrayList();
        List _list = new ArrayList();
        List list = new ArrayList();
        if (!isExist.equals("")) {
            if (type.equals("3")) {//标题
                list = helpSearchDomain.searchKnowlegeByKey("title", keyword, path, sp);
                if (list != null && list.size() > 0) {
                    int len = list.size();
                    for (int i = 0; i < len; i++) {
                        Map m = (Map) list.get(i);
                        Map map = new HashMap();
                        map.put("id", m.get("knowlegeid"));
                        map.put("title", "<a href=\"javascript:void(0)\" onclick=\'getKnowledgeInfo(" + m.get("knowlegeid") + ")\'>" + m.get("title") + "</a>");
                        map.put("infoType", m.get("infoType"));
                        map.put("createtime", m.get("createtime"));
                        _list.add(map);
                    }
                }
            } else if (type.equals("2")) {// 内容
                list = helpSearchDomain.searchKnowlegeByKey("contents", keyword, path, sp);
                if (list != null && list.size() > 0) {
                    int len = list.size();
                    for (int i = 0; i < len; i++) {
                        Map m = (Map) list.get(i);
                        Map map = new HashMap();
                        map.put("id", m.get("knowlegeid"));
                        map.put("title", "<a href=\"javascript:void(0)\" onclick=\'getKnowledgeInfo(" + m.get("knowlegeid") + ")\'>" + m.get("title") + "</a>");
                        map.put("infoType", m.get("infoType"));
                        map.put("createtime", m.get("createtime"));
                        _list.add(map);
                    }
                }
            } else { //全文
                list = helpSearchDomain.searchKnowlegeByKey("all", keyword, path, sp);
                if (list != null && list.size() > 0) {
                    int len = list.size();
                    for (int i = 0; i < len; i++) {
                        Map m = (Map) list.get(i);
                        Map map = new HashMap();
                        map.put("id", m.get("knowlegeid"));
                        map.put("title", "<a href=\"javascript:void(0)\" onclick=\'getKnowledgeInfo(" + m.get("knowlegeid") + ")\'>" + m.get("title") + "</a>");
                        map.put("infoType", m.get("infoType"));
                        map.put("createtime", m.get("createtime"));
                        _list.add(map);
                    }
                }
            }
            returnlist.add(_list);
            returnlist.add(sp);
            return returnlist;
        } else {
            return "";
        }
    }

 

有不懂得地方加:QQ413540158