Ajax应用案例——仿百度搜索提示

需求分析:

在输入框输入关键字,使用Ajax发送异步请求,将输入框的关键字传递给服务端,查询数据库把查询到的相关信息转换为json字符串,响应给客户端,在客户端处理响应,即实现了下拉框中异步显示与该关键字相关信息。
在这里插入图片描述

代码示例:

在这里插入图片描述

  • 搜索页面(search.html)
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>AJAXDemo</title>
    <style type="text/css">
        .content{
            width:643px;
            margin:50px auto;
            text-align: center;
        }
        input[type='text']{
            width:530px;
            height:40px;
            font-size: 14px;
        }
        input[type='button']{
            width:100px;
            height:46px;
            background: #38f;
            border: 0;
            color: #fff;
            font-size: 15px
        }
        .result_tips{
            position: absolute;
            width: 535px;
            border: 1px solid #999;
            border-top: 0;
            display: none;

        }
        .result_tips div:hover{
            background-color: #ccc;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="content">
    <input type="text" name="word" id="searchWord">
    <input type="button" value="百度一下">
    <div class="result_tips">

    </div>
</div>

<script type="text/javascript" src="./js/jquery-3.3.1.js"></script>

<script type="text/javascript">
    //当键盘按钮松开时,发生 keyup 事件。(keyup()方法触发 keyup 事件)
    $("#searchWord").keyup(function () {
        if(this.value===""){
            //输入框没有输入文字,则隐藏结果提示
            $(".result_tips").html("").hide();
            return;
        }
        var params="username="+this.value;
        $.post("searchServlet",params,function (result) {
            if(result!=null&&result.length>0){
                var htmlDiv="";
                for (var i = 0; i <result.length ; i++) {
                   var name= result[i].username;
                    htmlDiv+="<div>"+name+"</div>"
                }
                $(".result_tips").html(htmlDiv).show();
            }else{
                $(".result_tips").html("").hide();
            }
        },"json")
    });

    //给后来添加的元素(未来元素)绑定事件
    $(".result_tips").on("click","div",function () {
        $("#searchWord").val(this.innerHTML);
        $(".result_tips").html("").hide();
    })

</script>

</body>
</html>
  • 视图层(SearchServlet)
@WebServlet(name = "SearchServlet",urlPatterns = "/searchServlet")
public class SearchServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1.接收参数
        String username = request.getParameter("username");

        //2.完成功能
        SearchService searchService = new SearchService();
        List<User> list=searchService.search(username);

        //3.处理结果
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(list);
        response.getWriter().print(json);
        System.out.println(json);
        /*输出示例:
        [{"id":4,"username":"上官婉儿","password":"1"},
        {"id":5,"username":"上官锅儿","password":"1"},
        {"id":6,"username":"上官瓢儿","password":"1"},
        {"id":21,"username":"上官盖儿","password":"1"}]
        */
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
  • 业务逻辑层(UserService)
public class SearchService {
    public List<User> search(String username) {
        Searchdao searchdao = new Searchdao();
        List<User> list=searchdao.findUserByUserName(username);
        return list;
    }
}
  • 数据访问层(Userdao)
public class Searchdao {
    public List<User> findUserByUserName(String username)  {
        List<User> userList=null;
        try {
            DataSource dataSource = JDBCUtils.getDataSource();
            QueryRunner queryRunner = new QueryRunner(dataSource);
            String selectSql = "select * from t_user where username like  ?";
            userList = queryRunner.query(selectSql, new BeanListHandler<>(User.class), "%"+username+"%");
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            return userList;
        }
    }
}
public class JDBCUtils {
    //使用Druid数据库连接池技术获取数据库连接
    private static DataSource createDataSource;
    static{
        try {
            Properties pros = new Properties();
            //InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
            InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pros.load(is);
            createDataSource = DruidDataSourceFactory.createDataSource(pros);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() throws SQLException {
        return createDataSource.getConnection();
    }

    public static DataSource getDataSource() throws SQLException {
        return createDataSource;
    }

    //使用dbutils.jar中提供的DbUtils工具类,实现资源的关闭
    public static void closeResource(Connection conn, Statement ps, ResultSet rs){
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(ps);
        DbUtils.closeQuietly(rs);
    }

    public static void closeResource(Connection conn){
        DbUtils.closeQuietly(conn);
    }

    public static void closeResource(Connection conn,ResultSet rs){
        DbUtils.closeQuietly(conn);
        DbUtils.closeQuietly(rs);
    }
}
  • Druid数据库连接池配置文件(druid.properties)
url=jdbc:mysql:///stusmanager
username=root
password=root
driverClassName=com.mysql.jdbc.Driver
initialSize=10
maxActive=10
  • 实体类(User)
public class User {
    private int id;
    private String username;
    private String password;

    public User() {
    }

    public User(int id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}


@WebFilter(urlPatterns = "/*")
public class EncodingFilter implements Filter {
    @Override
    public void destroy() {
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //统一解决乱码问题
        //1.解决响应的中文乱码
        response.setContentType("text/html;charset=utf-8");
        //2.解决请求的中文乱码:post方式
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            request.setCharacterEncoding("utf-8");
        }
        //3.放行请求
        chain.doFilter(request, response);
    }
    @Override
    public void init(FilterConfig config) throws ServletException {
    }
}

数据库中的数据:
在这里插入图片描述


测试效果:

访问http://localhost:8080/test/search.html测试:
在这里插入图片描述

发布了48 篇原创文章 · 获赞 18 · 访问量 2936

猜你喜欢

转载自blog.csdn.net/qq_45615417/article/details/104673906