类似于百度的搜索引擎模糊查询功能,不过百度的模糊查询功能更强大,这里简单实现下.
要实现模糊查询,首先要做的就是把SQL写好。话不多少,直接贴代码了!
JSP页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>Sevlet类:My JSP 'search.jsp' starting page Ajax自动搜索提示
package servlet.ajax;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class Search extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String req=request.getParameter("txtSearch"); PrintWriter out = response.getWriter(); SearchDao sd=new SearchDao(); sd.getText(req); StringBuffer sb=sd.getText(req); out.print(sb.toString()); out.flush(); }}
进行连接数据库,模糊查询的JAVA类:
package servlet.ajax;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;public class SearchDao { public StringBuffer getText(String req){ //首先定义下连接数据的URL、用户名、密码 String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"; String user="scott"; String password="yulei123"; String sql="select ename from emp a where a.ename like ?"; if(req.trim().length()==0){ sql=sql+" and 1<>1"; } List strList=new ArrayList(); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection(url,user,password); PreparedStatement pre=con.prepareStatement(sql); pre.setString(1,"%"+req.toUpperCase().trim()+"%"); ResultSet rs=pre.executeQuery(); while(rs.next()){ String ename=rs.getString("ename"); strList.add(ename); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } StringBuffer sb=new StringBuffer(); int size=strList.size(); for(int i=0;i代码写好后,就可以在文本框输入字母后就可以模糊查询出数据了!