html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/jquery-3.7.0.js"></script>
<script>
$(function () {
$("#search").bind("input propertychange", function () {
//获取输入框输入的值
var name = $(this).val();
//判断获取的值是否为空
if (name != null && name != "") {
//清理
$("#show").html("");
//从后台获取数据
$.get("SearchServlet", {"name": name}, function (date) {
//判断是否为空
if (date != name && date != "") {
for (var i = 0; i < date.length; i++) {
$("#show").append("<div>"+date[i]+"</div>")
}
}
}, "json");
}else {
//清理
$("#show").html("");
}
})
});
</script>
</head>
<body>
<div id="box">
<input id="search" type="text" name="search">
<button id="btn">百度一下</button>
</div>
<div id="show">
</div>
</body>
</html>
后台
java
package com.etime.servlet;
import com.etime.dao.StudentDao;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet(name = "SearchServlet", value = "/SearchServlet")
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//防止乱码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
StudentDao studentDao = new StudentDao();
String name = request.getParameter("name");
List studentByName = studentDao.getStudentByName(name);
if (studentByName != null) {
ObjectMapper mapper = new ObjectMapper();
String res = mapper.writeValueAsString(studentByName);
PrintWriter writer = response.getWriter();
writer.print(res);
writer.close();
}
}
}
dao
java
package com.etime.dao;
import com.etime.QueryRunnerUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import java.sql.SQLException;
import java.util.List;
public class StudentDao {
QueryRunner queryRunnerUtils = QueryRunnerUtils.getQueryRunner();
public List getStudentByName(String name){
String sql = "select sname from tb_student where sname like ?";
List sname = null;
try {
sname = queryRunnerUtils.query(sql, new ColumnListHandler("sname"), "%" + name + "%");
} catch (SQLException e) {
e.printStackTrace();
}
return sname;
}
}