使用Ajax+Servlet访问MySQL数据库实现简易搜索框

最近在准备研究生复试的时候偶然看到关于Ajax技术的一篇文章,故也想来小试牛刀看看到底是怎么一回事

这一段我就直接copy网上的介绍了,省得码字

什么是Ajax:Ajax(Asynchronous Javascrpt And Xml)是一种运用于浏览器的技术,它可以在浏览器与服务器之间使用异步通信机制进行数据通信,从而允许浏览器向服务器获取少量信息而不是刷新整个页面。Ajax并不是一种新的技术,或者说它不是一种技术,它只是多种技术的综合:Javascript、Html、Css、Dom、Xml、XMLHttpRequest等技术按照一定的方式在协作中发挥各自的作用就构成了Ajax。

接下来就废话少说,直接进入正题

我们先从前端页面开始吧,新建一Web项目,在Webcontent里新建一search.jsp文件,下面是项目所需的文件图片


search.jsp文件

<script type="text/javascript">
		var xmlHttp;
		function getMoreContent() {
			var content = document.getElementById("keyword").value;
			if(content==""){
				cleanKeyContent();
				return;
			}
			xmlHttp = getXmlHttp();		//获取XmlHttp对象实现Ajax异步传输数据
			var url = "AjaxTest1?keyword="+encodeURI(encodeURI(content));	//encodeURI解决中文关键字乱码问题
			xmlHttp.open("GET", url, true);
			xmlHttp.onreadystatechange = callback;		//调用onreadystatechange的回调函数
			xmlHttp.send(null);
		}
		
		//获取XmlHttp对象实现Ajax异步传输数据
		function getXmlHttp() {
			var xmlHttp;
			if(window.XMLHttpRequest){			//这种情况针对于目前主流浏览器都适用
				xmlHttp = new XMLHttpRequest();
			}
			if(window.ACTIVEXObject){
				xmlHttp = new ACTIVEXObject("Microsoft.XMLHttp");
				if(!xmlHttp){
					xmlHttp = new ACTIVEXObject("Msxml2.XMLHttp");
				}
			}
			return xmlHttp;
		}
		
		function callback() {
			if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
				var result = xmlHttp.responseText;		//获取服务器返回的文本数据
				var jsonData = eval("(" +result+ ")");	//解析获取的Json数据
				document.getElementById("test").innerHTML = jsonData;
			}
		}
		
		function cleanKeyContent() {
			document.getElementById("test").innerHTML = "";
		}
	</script>
</head>
<body>
	<div id="myDiv">
		<input type="text" size="50" id="keyword" onkeyup="getMoreContent()" onblur="cleanKeyContent()" onfocus="getMoreContent()"/>
		<input type="button" value="百度一下" width="50px"/>
		<p id="test">新哥要变的内容</p>
	</div>
</body>

这里要注意的地方是

var url = "AjaxTest1?keyword="+encodeURI(encodeURI(content)); //encodeURI解决中文关键字乱码问题

String keyword = request.getParameter("keyword");

keyword = URLDecoder.decode(keyword, "UTF-8"); //解决中文搜索问题

它们共同解决了jsp与servlet服务器通信时中文乱码问题,否则搜索框将实现不了中文搜索功能

下面是AjaxTest1.servlet文件

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		String keyword = request.getParameter("keyword");
		keyword = URLDecoder.decode(keyword, "UTF-8");			//解决中文搜索问题
		datas.clear();						//每次访问服务器时都要将datas集合清空否则datas集合中元素会一直增加	
		connectDatabase(keyword);			//连接MySQL数据库访问数据库内容	
		if(datas.size()>0){					//访问到数据库中数据的时候方可将数据发送到客户端
			Gson gson = new Gson();
			String data = gson.toJson(datas);
			PrintWriter write = response.getWriter();
			write.write(data);
		}
		
	}

	//连接MySQL数据库访问数据库内容
	private void connectDatabase(String keyword) {
		Connection connection = null;
		PreparedStatement prep = null;
		String Sql = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://localhost/firsttable?useSSL=false";
			connection = DriverManager.getConnection(url, "root", "xinge666");			
			Sql = "SELECT * FROM keyword WHERE Keyword LIKE ?";
			prep = (PreparedStatement) connection.prepareStatement(Sql);
			prep.setString(1, '%' +keyword+ '%');
			ResultSet result = prep.executeQuery();			
			while (result.next()) {
				if(!datas.contains(result.getString("Keyword"))){
					datas.add(result.getString("Keyword"));
				}			
			}			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			if(connection != null){
				try {
					connection.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (prep != null) {
				try {
					prep.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

这里要注意的地方是:

1. String url = "jdbc:mysql://localhost/firsttable?useSSL=false";

    这一句很重要,如果不加这一句很可能会出现以下情况

    Establishing SSL connection without server's identity verification is not recommended.

2. Sql = "SELECT * FROM keyword WHERE Keyword LIKE ?";

    prep.setString(1, '%' +keyword+ '%');

    这个是LIKE关键字的用法

猜你喜欢

转载自blog.csdn.net/weixin_36431280/article/details/79598072
今日推荐