最近要做一个能让搜索框输入数据自动补全的功能(类似百度搜索):
先看看写完后的demo效果:
这样的方法如何实现? 首先要使用连接池,需要导入jar包:
然后编写连接池的类 C3P0Util.java:
import java.sql.SQLException;
import java.sql.Connection;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Util {
private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
public static DataSource getDataSource() {
return dataSource;
}
public static Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
为它配置一个xml用于连接数据库,将其放在src下:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://xxx.x.x.x:xxxx(你的本地地址,和你的jdbc配置一样)/你的数据库名?useSSL=false</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
</c3p0-config>
写一个方法,是提示框显示的数据
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<Object> findDeseaseAjax(String menber) {
QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
try {
return qr.query("select idnum from fmenber where menber like ?", new ColumnListHandler(),"%"+menber+"%");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
然后是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.gxuwz.medical.web.serviceImpl.DiseaseServer;
public class FindPatientAjaxServlet extends HttpServlet {
public FindPatientAjaxServlet() {
super();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
//获取搜索框输入的内容
String menber=request.getParameter("menber");
menber=new String(menber.getBytes("iso-8859-1"), "utf-8");
//向server层调用相应的业务
DiseaseServer diseaseServer=new DiseaseServer();
String res=diseaseServer.findDiseaseAjax(menber);
//返回结果
response.getWriter().write(res);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
然后是server层,将获取到的数据转换一下:
import java.util.List;
import com.gxuwz.medical.domain.disease.Disease;
public class DiseaseServer {
public String findDiseaseAjax(String menber) {
Disease disease=new Disease();
List<Object> nameList=disease.findDeseaseAjax(menber);
String res="";
for (int i=0;i<nameList.size();i++) {
if(i>0){
res+=","+nameList.get(i);
}else{
res+=nameList.get(i);
}
}
return res;
}
}
然后是jsp的ajax方法:
<script>
$("#inputtable")
.keyup(
function() {
var content = $(this).val();
//如果当前搜索内容为空,无须进行查询
if (content == "") {
$("#tips").css("display", "none");
return;
}
var div = document.getElementById("tips");
//由于浏览器的缓存机制 所以我们每次传入一个时间
var time = new Date().getTime();
$.ajax({
type : "get",
//新建一个名为findBooksAjaxServlet的servlet
url : "${pageContext.request.contextPath}/FindReimDisAjaxServlet",
data : {
idnum : content,
time : time
},
success : function(data) {
//拼接html
var res = data.split(",");
var html = "";
var ts = "当前为根据身份证号查询的慢病号:";
for (var i = 0; i < res.length; i++) {
//每一个div还有鼠标移出、移入点击事件
html += "<div onclick='setSearch_onclick(this)' onmouseout='changeBackColor_out(this)' onmouseover='changeBackColor_over(this)'>"
+ res[i] + "</div>";
}
if (i = 0) {
ts = none;
}
div.innerHTML = ts + html;
div.style.display = "block";
}
});
});
function changeBackColor_over(div) {
$(div).css("background-color", "#CCCCCC");
}
//鼠标移出时回复div颜色
function changeBackColor_out(div) {
$(div).css("background-color", "");
}
//当鼠标带点击div时,将div的值赋给输入文本框
function setSearch_onclick(div) {
$("#inputtable").val(div.innerText);
$("#tips").css("display", "none");
}
</script>
最后是用于显示的jsp:
<form id="form-find" method="post" class="form-x"
action="<%=path%>/ReimburseServlet?m=find">
<div
style="width:100%; border:solid 1px #ddd;background-color: #F9F9F9;border-radius:2px;padding: 4px;margin-bottom:10px;">
<input type="text" class="input" style="width:250px; line-height:17px;display:inline-block" name="disCode" id="inputtable" />
<input class="button button-serch bg-main text-big input-small"
type="submit" id="bt" value="审核">
<div id="tips" display: none; class="input" style="width:250px; line-height:17px;"></div>
</div>
</form>
这样就完成了,js和搜索数据库的方法可以自定义,按需求即可。