前台代码:(注意要导入JQuery包,在lib中也要导入gson-x.x.x.jar包)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="JS/jquery-1.11.0.js"></script>
<script type="text/javascript">
//为搜索绑定聚焦事件
$(function(){
$("#search").keyup(function(){
var content = $(this).val();
var returnStr = "";
$.post(
"/ajax_backstage1/ajaxServlet",
{"content":content},
function(data){
if(data.length>0){
for(var i=0;i<data.length;i++){
returnStr += "<div id='div' style='padding:5px;cursor:pointer' onmouseover='overFn(this)' onmouseout='outFn(this)' onclick='clickFn(this)'>"+data[i]+"</div>";//
}
$("#div").html(returnStr);
$("#div").css("display","block");
}else{
$("#div").css("display","none");
}
},
"json"
);
});
$("#search").blur(function(){
$("#div").css("display","none");
});
})
//绑定按钮事件
$(function(){
$("#button").click(function(){
var sub = $("#search").val();
$.ajax({
type:"POST",
url:"{pageContext.request.contextPath}/ajaxServlet",
contentType:"application/json",
data:JSON.stringify({"sub":sub}),
dataType:"json",
success:function(result){
//请求正确后的操作
},
error:function(result){
//请求失败后的操作
}
});
});
})
//对div添加鼠标移入效果
function overFn(obj){
$(obj).css("background-color","yellow");
}
//对div添加鼠标移出效果
function outFn(obj){
$(obj).css("background-color","#F0F8FF");
}
//对div内容添加点击效果
function clickFn(obj){
$("#search").val($(obj).html());
$("#div").css("display","none");
}
</script>
<body>
<input type="text" id="search" /><input type="button" id="button" value="按钮">
<div id="div" style="width:150px;display:none;background-color: #F0F8FF"></div>
</body>
</html>
下面是后台MVC分层思想的Servlet+JDBC代码
servlet层:
package action;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import service.SearchService;
/**
* Servlet implementation class ajaxServlet
*/
public class ajaxServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ajaxServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从前台获取json格式数据
request.setCharacterEncoding("UTF-8");
String content = (String) request.getParameter("content");
//创建一个service类,并调用其查询方法
SearchService ss = new SearchService();
List<String> list = null;
try {
list = ss.search(content);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(list);
//将service返回的数据进行格式转换变成json
//先创建一个Gson
Gson gson = new Gson();//这里没有gson导包操作会报错
//然后解析获得的list,把json转换成string
String str = gson.toJson(list);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(str);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
service层:
package service;
import java.sql.SQLException;
import java.util.List;
import dao.SearchDao;
public class SearchService {
public List<String> search(String content) throws SQLException {
// TODO Auto-generated method stub
SearchDao sd = new SearchDao();
List<String> list = sd.search(content);
return list;
}
}
dao层:
package dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import utils.DataBaseUtil;
public class SearchDao extends DataBaseUtil {
public List<String> search(String content) throws SQLException {
// TODO Auto-generated method stub
List<String> list = new ArrayList<String>();
String sql = "select * from cst_linkman where lkm_name like '%"+content+"%'" ;
rs = commonQuery(sql);
while(rs.next()){
list.add(rs.getString("lkm_name"));
}
return list;
}
}
package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DataBaseUtil {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String DRIVER_URL = "jdbc:mysql://127.0.0.1:3306/test";
private static final String DRIVER_USER = "root";
private static final String DRIVER_PWD = "123";
protected Connection conn=null;
protected PreparedStatement pst=null;
protected ResultSet rs=null;
static{
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//链接数据库
public static Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(DRIVER_URL,DRIVER_USER,DRIVER_PWD);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
//查询
public ResultSet commonQuery(String sql,Object...params) throws SQLException{
conn = getConnection();
pst=conn.prepareStatement(sql);
if(params !=null && params.length>0){
setValue(pst,params);
}
rs=pst.executeQuery();
return rs;
}
//增删改
public int commonUpdate(String sql,Object...params) throws SQLException{
int result =0;
conn=getConnection();
try {
pst=conn.prepareStatement(sql);
if(params !=null && params.length>0){
setValue(pst,params);
}
result=pst.executeUpdate();
}finally{
closeAll(conn, pst, rs);
}
return result;
}
private void setValue(PreparedStatement pst2, Object[] params) throws SQLException {
for(int i=0;i<params.length;i++){
pst2.setObject(i+1, params[i]);
}
}
//关闭数据库
public void closeAll(Connection conn,PreparedStatement pst,ResultSet rs){
try {
if(rs !=null){
rs.close();
}
if(pst !=null){
pst.close();
}
if(conn !=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
另外,这里用的是2.5版本的web项目,代码没有添加注解,映射servlet的web.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>ajax_backstage1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>ajaxServlet</display-name>
<servlet-name>ajaxServlet</servlet-name>
<servlet-class>action.ajaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ajaxServlet</servlet-name>
<url-pattern>/ajaxServlet</url-pattern>
</servlet-mapping>
</web-app>