您的位置:首页 > Web前端 > JQuery

JQuery UI AutoComplete 与 Strtus2 结合使用

2013-01-20 17:00 781 查看
这篇文章中完成一个搜索城市的示例程序,输入城市名称或者拼音首字母,返回城市的智能提示。使用了JQuery UI AutoComplete插件。

首先,看一下效果图,了解程序完成后是一个什么样子。

汉字搜索



拼音首字母搜索



看完了效果图,下面一步一步介绍如何完成这个程序。

Step 1 数据库表及函数(SQL Server 2008)

先来建立数据库表City,它包含两个字段CityID,CityName。

CREATE TABLE City
(
CityID INT IDENTITY(1,1) Primary KEY ,  --城市主键
CityName NVARCHAR(50)  NOT NULL,    --城市名称
)


然后再插入一些示例数据

INSERT City(CityName) Values('北京市')
INSERT City(CityName) Values('天津市')
INSERT City(CityName) Values('上海市')
INSERT City(CityName) Values('重庆市')
INSERT City(CityName) Values('邯郸市')
INSERT City(CityName) Values('石家庄市')
INSERT City(CityName) Values('保定市')
INSERT City(CityName) Values('张家口市')
INSERT City(CityName) Values('承德市')
INSERT City(CityName) Values('唐山市')
//省略...


从表结构及示例数据来看,这里没有城市名称拼音首字母字段,那如何完成拼音搜索呢?不要着急,这得在数据库中建立一个函数,用来返回汉字的拼音首字母。

返回汉字拼音首字母函数 f_GetPy [注1]

create   function  f_GetPy(@str   nvarchar(4000))
returns   nvarchar(4000)
as
begin
declare   @strlen   int,@re   nvarchar(4000)
declare   @t   table(chr   nchar(1)   collate   Chinese_PRC_CI_AS,letter   nchar(1))
insert   into   @t(chr,letter)
select   '吖', 'A '   union   all   select   '八', 'B '   union   all
select   '嚓', 'C '   union   all   select   '咑', 'D '   union   all
select   '妸', 'E '   union   all   select   '发', 'F '   union   all
select   '旮', 'G '   union   all   select   '铪', 'H '   union   all
select   '丌', 'J '   union   all   select   '咔', 'K '   union   all
select   '垃', 'L '   union   all   select   '嘸', 'M '   union   all
select   '拏', 'N '   union   all   select   '噢', 'O '   union   all
select   '妑', 'P '   union   all   select   '七', 'Q '   union   all
select   '呥', 'R '   union   all   select   '仨', 'S '   union   all
select   '他', 'T '   union   all   select   '屲', 'W '   union   all
select   '夕', 'X '   union   all   select   '丫', 'Y '   union   all
select   '帀', 'Z '
select   @strlen=len(@str),@re= ' '
while   @strlen> 0
begin
select   top   1   @re=letter+@re,@strlen=@strlen-1
from   @t   a   where   chr <=substring(@str,@strlen,1)
order   by   chr   desc
if   @@rowcount=0
select   @re=substring(@str,@strlen,1)+@re,@strlen=@strlen-1
end
return(@re)
end


如果调用f_GetPy('北京'),则返回拼音首字母 'bj'

Step 2 前端页面

前端页面非常简单,只需要一个输入框就可以了。这里使用的Struts2 html标签。当然,你也可以使用原生html标签。

<s:textfield name="cityName" id="cityName"></s:textfield>


cityName的值提交到服务器,作为搜索关键字。为了实现Ajax智能提示,需要用到JQuery UI AutoComplete插件,它要求返回JSON格式的数据。所以,下一步就是要在Action中返回JSON数据。

Step 3 Action

CityAction接收搜索关键字,并返回JSON数据。

package com.dong.action;

import java.util.ArrayList;
import java.util.List;
import org.apache.struts2.json.annotations.JSON;
import com.dong.po.City;
import com.dong.service.ICityService;
import com.opensymphony.xwork2.ActionSupport;

/**
* 城市搜索Action
* @version 1.0 2013/01/12
* @author dongliyang
*
*/
public class CityAction extends ActionSupport{

/** SerialVersionUID*/
private static final long serialVersionUID = -8042695641942800870L;
/** 城市Service */
private ICityService cityService;
/** 搜索关键字,城市名称 */
private String cityName;
/** 城市列表 */
private List<City> cityList;
/** 智能提示列表,以JSON数据格式返回 */
private List<String> autoSuggests = new ArrayList<String>();

/**
* 智能提示,自动补全功能
* @return String
*/
public String autoComplete(){

cityList = cityService.findByName(cityName);

for(City city : cityList){
autoSuggests.add(city.getCityName());
}

return SUCCESS;
}

public void setCityService(ICityService cityService) {
this.cityService = cityService;
}

//搜索关键字不作为JSON数据返回,设置serialize=false
@JSON(serialize=false)
public String getCityName() {
return cityName;
}

public void setCityName(String cityName) {
this.cityName = cityName;
}

//搜索结果列表不作为JSON数据返回,设置serialize=false
@JSON(serialize=false)
public List<City> getCityList() {
return cityList;
}

public void setCityList(List<City> cityList) {
this.cityList = cityList;
}

//智能提示列表作为JSON数据返回,设置serialize=true
@JSON(serialize=true)
public List<String> getAutoSuggests() {
return autoSuggests;
}

public void setAutoSuggests(List<String> autoSuggests) {
this.autoSuggests = autoSuggests;
}
}


CityAction中,cityName接收搜索关键字,不需要向页面返回数据,因此需要设置serialize=false,不进行序列化。

Action返回的JSON数据,格式是这样的 {"autoSuggests":["北京市","毕节地区","宝鸡市"]}

由于CityAction返回的是JSON数据,因此需要在struts.xml中进行一些特殊配置,Action所在包需要继承自json-default。

struts.xml配置文件

<package name="search" namespace="/search" extends="json-default">
<action name="cityAction" class="cityAction">
<result name="success" type="json"></result>
</action>
</package>


CityAction依靠CityService返回城市列表,Service层没有什么可介绍的,只是简单调用了一下Dao层。重点看一下Dao层是如何实现搜索的。

CityDaoImpl

package com.dong.dao.impl;

import java.util.List;

import com.dong.dao.ICityDao;
import com.dong.framework.BaseDao;
import com.dong.po.City;

public class CityDaoImpl extends BaseDao<City> implements ICityDao {

/**
* 根据名称或拼音搜索城市
* @param cityName
* @return List<City> 城市列表
*/
public List<City> findByName(String cityName){

String hql = "from City c where c.cityName like ? or dbo.f_GetPy(c.cityName) like ?";
return find(hql, "%" + cityName + "%",cityName + "%");

}

}


hql语句中,使用cityName和f_GetPy(cityName) 来跟关键字进行like匹配。

比如:汉字搜索时,关键字"北京"传入方法,hql where子句中的c.cityName将能够匹配。

拼音搜索时,关键字"BJ"传入方法,hql where子句中的dbo.f_GetPy(c.cityName)将能够匹配。

特别说明:Hibernate有一些内置函数,比如max、min,Hibernate能够将这些函数转换成对应数据库的函数。当不能识别函数名时(本例中f_GetPy),将交给底层数据库来处理。

到现在为止,数据库已经能够正确返回JSON数据了。应该集成JQuery UI AutoComplete了。

Step 4 JQuery UI AutoComplete

Search.jsp页面如下

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
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>城市搜索页</title>
<link rel="stylesheet" href="css/jquery-ui.css" />
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.custom.js"></script>
<style type="text/css">
body { text-align:center;background:#efefef;}
h2 { color:#676463;}
#cityDiv { margin-right:auto;margin-left:auto;}
#cityName
{
font-family: Verdana,Arial,sans-serif;
font-size: 1.1em;
}
</style>
<script type="text/javascript">
$(function(){
$("#cityName").autocomplete({
minLength:1,
autoFocus:true,
source:function(request,response){
$.ajax({
type:"POST",
url:"search/cityAction!autoComplete.action",
dataType:"json",
data:{ cityName :  $("#cityName").val() },
success:function(json){
response($.map(json.autoSuggests,function(item){
return {
label:item,
value:item
};
}));
}
});
}
});
});
</script>
</head>
<body>
<h2>JQuery UI AutoComplete + Struts2 智能提示</h2>
<div id="cityDiv">
<div id="noteDiv">
<img alt="where are you from?" src="images/searchMap.png">
</div>
<s:textfield name="cityName" id="cityName"></s:textfield>
</div>
</body>
</html>


首先,引入css、js文件。

其次,在输入框元素上调用autocomplete方法。minLength指定文本框中有多少个字符时,发送请求。autoFocus:true,选中第一个匹配结果。source指定数据来源。JQuery UI Autocomplete插件需要返回带有label和value的对象。success函数的参数json是服务器端传过来的数据,比如是{"autoSuggests":["北京市","毕节地区","宝鸡市"]},因此,使用$.map处理的时候,应该定位到json.autoSuggests。item就是"北京市"、"毕节地区"、"宝鸡市"。

结束:本示例使用了SSH + JQuery UI AutoComplete完成了智能提示效果,限于篇幅,Hibernate、Spring略去不提。下面提供了示例程序的下载,包括数据库脚本及可运行的程序。为了在你的机器上运行,请修改hibernate.properties文件,填写正确的数据库用户名及密码。

下载:百度网盘 (大小:17.97MB)

注1:获取汉字拼音首字母的函数,来自:http://www.cnblogs.com/wuhuacong/archive/2010/01/25/1655916.html。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: