实现一个简单搜索页面小案例,在文本框中输入一个值以后(键盘抬起的时候),给出一些提示,主要使用了Ajax和Servlet技术,后端用过json响应给前端,实现异步
create table words(
id int primary key auto_increment,
word varchar(50)
);
insert into words values (null, 'all');
insert into words values (null, 'after');
insert into words values (null, 'app');
insert into words values (null, 'apple');
insert into words values (null, 'application');
insert into words values (null, 'applet');
insert into words values (null, 'and');
insert into words values (null, 'animal');
insert into words values (null, 'back');
insert into words values (null, 'bad');
insert into words values (null, 'bag');
insert into words values (null, 'ball');
insert into words values (null, 'banana');
insert into words values (null, 'bear');
insert into words values (null, 'bike');
insert into words values (null, 'car');
insert into words values (null, 'card');
insert into words values (null, 'careful');
insert into words values (null, 'cheese');
insert into words values (null, 'come');
insert into words values (null, 'cool');
insert into words values (null, 'dance');
insert into words values (null, 'day');
insert into words values (null, 'dirty');
insert into words values (null, 'duck');
insert into words values (null, 'east');
insert into words values (null, 'egg');
insert into words values (null, 'every');
insert into words values (null, 'example');
package com.DJL.pojo;
public class Words {
private int id;
private String word;
public Words() {
}
public Words(int id, String word) {
this.id = id;
this.word = word;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
}
服务器要响应哪些数据给客户端?
package com.DJL.pojo;
public class ResultBean {
/**
* 服务器端是否出现异常
*/
private Boolean flag;
/**
* 服务器端处理请求之后要响应的数据
*/
private Object data;
/**
* 服务器端的异常信息
*/
private String errorMsg;
@Override
public String toString() {
return "ResultBean{" +
"flag=" + flag +
", data=" + data +
", errorMsg='" + errorMsg + '\'' +
'}';
}
public Boolean getFlag() {
return flag;
}
public void setFlag(Boolean flag) {
this.flag = flag;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public ResultBean(Boolean flag, Object data, String errorMsg) {
this.flag = flag;
this.data = data;
this.errorMsg = errorMsg;
}
public ResultBean(Boolean flag) {
this.flag = flag;
}
public ResultBean(Boolean flag, Object data) {
this.flag = flag;
this.data = data;
}
public ResultBean(Boolean flag, String errorMsg) {
this.flag = flag;
this.errorMsg = errorMsg;
}
}
链接:jar、jquery库
提取码:lzdj
WordsDao.java:
package com.DJL.dao;
import com.DJL.pojo.Words;
import com.DJL.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class WordsDao {
QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
public List<Words> search(String keyword) throws Exception {
String sql = "select * from words where word like ? limit 0,11";//模糊查询
List<Words> wordsList = qr.query(sql, new BeanListHandler<Words>(Words.class),"%"+ keyword+"%");
return wordsList;
}
}
WordsService.java:
package com.DJL.service;
import com.DJL.dao.WordsDao;
import com.DJL.pojo.Words;
import java.util.List;
public class WordsService {
WordsDao wordsDao = new WordsDao();
public List<Words> search(String keyword) throws Exception {
List<Words> wordsList = wordsDao.search(keyword);
return wordsList;
}
}
WordsServlet.java:
package com.DJL.web.servlet;
import com.DJL.pojo.ResultBean;
import com.DJL.pojo.Words;
import com.DJL.service.WordsService;
import com.alibaba.fastjson.JSON;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
@WebServlet("/words")
public class WordsServlet extends HttpServlet {
private WordsService wordsService = new WordsService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
//通过反射改进之后的代码
try {
//根据方法名获取方法
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//执行方法
method.invoke(this,req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
/**
* @description:查询关键字集合
* @param: [req, resp]
* @return: void
*/
public void search(HttpServletRequest req, HttpServletResponse resp) throws IOException {
ResultBean resultBean = new ResultBean(true);
try {
String keyword = req.getParameter("keyword");
System.out.println(keyword);
List<Words> wordsList = wordsService.search(keyword);
resultBean.setData(wordsList);
} catch (Exception e) {
resultBean.setFlag(false);//服务器出现异常
resultBean.setErrorMsg("查询失败");
e.printStackTrace();
}
String jsonStr = JSON.toJSONString(resultBean);
System.out.println(jsonStr);
resp.getWriter().write(jsonStr);
}
}
druid.properties:(配置文件)
# 数据库连接参数
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
username=root
password=123456
driverClassName=com.mysql.jdbc.Driver
# 连接池的参数
initialSize=10
maxActive=10
maxWait=2000
工具类:DruidUtil.java
package com.DJL.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;
public class DruidUtil {
private static DataSource dataSource;
static {
try {
//1. 创建Properties对象
Properties properties = new Properties();
//2. 将配置文件转换成字节输入流
InputStream is = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
//3. 使用properties对象加载is
properties.load(is);
//druid底层是使用的工厂设计模式,去加载配置文件,创建DruidDataSource对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
}
package com.DJL.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
@WebFilter("/*")
public class EncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException, IOException {
//req就是服务器创建的请求对象,resp就是服务器创建的响应对象
//先将req和resp对象进行强转
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//使用request和response对象进行解决乱码的操作
request.setCharacterEncoding("UTF-8");
if (!request.getRequestURI().contains(".css")) {
response.setContentType("text/html;charset=UTF-8");
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<script src="js/jquery-3.3.1.js">script>
head>
<body>
<div align="center">
<div id="msg">div>
<input id="inputId" type="text" style="width: 500px; height: 38px;" onkeyup="searchWords(this.value)"/><input type="button" style="height: 38px;" value="搜索" />
<div id="divId" style="width: 500px; border: 1px red solid; height: 300px; position: absolute; left: 490px;">
<table id="tabId" width="100%" height="100%" border="1px">
table>
div>
div>
<script>
function searchWords(keyword){
if(keyword!=""){//内容不为空
$("#divId").show();
$.post("words","action=search&keyword="+keyword,function(result){
if (result.flag) {//服务器无异常
var data = result.data
$("#tabId").empty()
$.each(data,function(index,words){
//words就是每一个json对象
var word = words.word
$("#tabId").append($(""+word+""))
})
}else{//服务器有异常
$("#msg").html("网络异常")
}
},"json")
}else{//输入框为空,进行隐藏
$("#divId").hide();
}
}
script>
body>
html>