zoukankan      html  css  js  c++  java
  • 分页和异步验证注册

    1.分页

    分页条:【首页】【上一页】[1][2][3][4]【下一页】【尾页】
    分页功能的实现:
    物理分页:一次只查10条记录,点击下一页,再去查询后10条,使用sql语句进行控制的分页
    缺点:经常需要和数据库交互
    优点:数据量特别大,不会导致内存溢出
    逻辑分页:一次性将所有数据全都查询出来,根据需要进行截取.List集合进行控制. subList();
    缺点:数据量如果特别大,容易导致内存溢出.
    优点:与数据库交互次数少.
    不同的数据库对分页的语句也是不一样的
    MYSQL进行分页: 使用limit关键字.
    * select * from xxx limit a,b;


    根据页数计算 limit后面的两个参数:
    * currPage begin pageSize
        1    0      10
        2    10    10
        3    20    10
    * begin = (currPage - 1) * pageSize;
    参数的传递:
    * 前台--->后台:currPage
    * 后台--->前台:currPage,totalPage(总页数),totalCount(总记录数),pageSize,List
    使用JavaBean封装参数:
    * 后台--->前台:传递一个JavaBean就可以.

    实现:

    在index.jsp中添加一个分页访问数据的链接

    <a href="${ pageContext.request.contextPath }/ProductFindByPageServlet?currentPage=1">分页查询商品</a>

    在web.servlet层创建ProductFindByPageServlet

    public class ProductFindByPageServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * 分页的servlet
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                //获取表单数据
                int currentPage = Integer.parseInt(request.getParameter("currentPage"));
                //调用业务逻辑
                ProductService ps = new ProductService();
                PageBean pageBean = ps.findByPage(currentPage);
                //分发转向
                request.setAttribute("pageBean", pageBean);
                request.getRequestDispatcher("/jsp/product_page.jsp").forward(request, response);
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    
    }

    把当前页传递到service层,在service层处理业务逻辑
    因为在业务层需要把当前页,总页,总记录数等数据封装到一个pageBean中,所以首先先创建pageBean类

    public class PageBean {
        //当前页
        private int currentPage;
        //总记录数
        private int totalCount;
        //每页显示数
        private int pageSize;
        //总页数
        private int totalPage;
        //每页显示的数据信息
        private List<Product> list;
        public PageBean(int currentPage, int totalCount, int pageSize, int totalPage, List<Product> list) {
            super();
            this.currentPage = currentPage;
            this.totalCount = totalCount;
            this.pageSize = pageSize;
            this.totalPage = totalPage;
            this.list = list;
        }
        public PageBean() {
            super();
        }
        public int getCurrentPage() {
            return currentPage;
        }
        public void setCurrentPage(int currentPage) {
            this.currentPage = currentPage;
        }
        public int getTotalCount() {
            return totalCount;
        }
        public void setTotalCount(int totalCount) {
            this.totalCount = totalCount;
        }
        public int getPageSize() {
            return pageSize;
        }
        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }
        public int getTotalPage() {
            return totalPage;
        }
        public void setTotalPage(int totalPage) {
            this.totalPage = totalPage;
        }
        public List<Product> getList() {
            return list;
        }
        public void setList(List<Product> list) {
            this.list = list;
        }
        
    }

    编写业务层

        /**
         * 把当前页,总记录数,每页显示数,总页数,封装到pagebean,返回给servlet
         * @throws SQLException 
         * */
        public PageBean findByPage(int currentPage) throws SQLException {
            //创建pagebean对象
            PageBean pb = new PageBean();
            //设置当前页,封装到pagebean
            pb.setCurrentPage(currentPage);
            //设置每页显示数,并封装到pagebean
            int pageSize = 10;
            pb.setPageSize(pageSize);
            /**
             * 调用dao层获取到总记录数,封装到pagebean中
             * */
            int totalCount = pd.findCount();
            pb.setTotalCount(totalCount);
            //得到总页数,封装到pagebean
            /*Double numCount = (double) (totalCount/pageSize);
            int totalPage = numCount.intValue();*/
            double tc = totalCount;
            //向上取整
            Double num  = Math.ceil(tc/pageSize);
            int totalPage = num.intValue();
            pb.setTotalPage(totalPage);
            //获取limit的第一个参数(从第几条开始)
            int begin = (currentPage - 1) * pageSize;
            /**
             * 调用dao层,获取每页显示的product数据,封装到list中在封装到pagebean中
             * */
            //传入limit需要的开始页和每页显示的记录数
            List<Product> list = pd.findByPage(begin,pageSize);
            pb.setList(list);
            return pb;
        }

    //返回总记录数

    public int findCount() throws SQLException {
            String sql = "select count(*) from product";
            Long l = (Long) qr.query(sql, new ScalarHandler());
            return l.intValue();
        }
        //拿到分页的当前分页的数据
        public List<Product> findByPage(int begin, int pageSize) throws SQLException {
            String sql = "select * from product limit ?,?";
            Object [] params = {begin,pageSize};
            List<Product> list = qr.query(sql, new BeanListHandler<Product>(Product.class), params);
            return list;
        }

    2.AJAX异步验证注册

    首先是不使用jq的方式用 异步完成验证注册

    这是一个输入用户名界面的div

              <div>
                        请输入用户名:<input type="text" name="username" id="username" class="clickevent" />
                        <span id="show"></span>        
                    </div>

    为这个标签绑定一个失去焦点的事件

    document.getElementById("username").onblur = function() {
        
        //获取异步对象
        var xhr = createXMLHttp;
        //设置监听
        xhr.onreadystatechange = function() {
            var username = document.getElementById("username").value;
            if(xhr.readyState == 4 && xhr.status == 200) {
                var data = xhr.responseText;
                if(data == 1) {
                    document.getElementById("show").innerHTML = "<font color='green'>用户名可以使用</font>";
                }else {
                    document.getElementById("show").innerHTML = "<font color='red'>用户名已经被占用</font>";
                }
                document.getElementById("show").innerHTML = "bbb";
            }
        }
        xhr.open("POST","/AJAX/CheckServlet",true);
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xhr.send("username="+username);
        xhr.send("username="+username);
    }
    //提供一个异步对象创建的方法
    function createXMLHttp() {
        var xmlHttp;
        try { // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        } catch (e) {
            try {// Internet Explorer
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                }
            }
        }
        return xmlHttp;
    }

    编写CheckServlet

    public class CheckServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        /**
         * 异步校验用户名
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            String username = request.getParameter("username");
            System.out.println("username="+username);
            try {
                UserService us = new UserService();
                User user = us.checkUser(username);
                System.out.println(user);
                if(user == null) {
                    //response.getWriter().println(1);
                    response.getWriter().println("<font color='green'>用户名可以使用</font>");
                }else {
                    //response.getWriter().println(2);
                    response.getWriter().println("<font color='red'>用户名已经被占用</font>");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }

    业务层

    public class UserService {
        
        UserDao ud = new UserDao();
        public User checkUser(String username) throws SQLException {
            User user = ud.check(username);
            return user;
        }
        
    }

    dao层

    public class UserDao {
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    public User check(String username) throws SQLException {
    String sql = "select * from users where username = ?";
    
    Object [] params = {username};
    
    User user = qr.query(sql, new BeanHandler<User>(User.class), params);
    
    
    return user;
    }
    
    }

    但是jq框架让异步验证更简便,所以更推荐使用异步
    JQuery的AJAX
    JQuery的AJAX部分方法:
    * Jq的对象.load(路径,参数,回调函数);
    * $.get(路径,参数,回调函数,数据类型);
    * $.post(路径,参数,回调函数,数据类型);
    * $.ajax();
    * serialize(); -- JQ的AJAX传递参数的时候需要使用的方法.


    首先引入两个jq的文件

    <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
    <script type="text/javascript" src="${ pageContext.request.contextPath }/js/jquery.js"></script>

    编写jquery.js

    $(function () {
        //给用户名文本框添加事件
        $("#username").blur(function() {
            //获取文本框中的值
            var username = $(this).val();
            //调用方法
            $("#show").load("/AJAX/CheckServlet",{"username":username});
        });
    });
  • 相关阅读:
    【原】Ubuntu13.04安装、卸载Gnome3.8
    【原】安装、卸载、查看软件时常用的命令
    【原】中文Ubuntu主目录下的文档文件夹改回英文
    【原】Ubuntu ATI/Intel双显卡 驱动安装
    【转】Hadoop vs Spark性能对比
    【译】Spark调优
    【转】Spark源码分析之-scheduler模块
    【转】Spark源码分析之-deploy模块
    【转】Spark源码分析之-Storage模块
    【转】弹性分布式数据集:一种基于内存的集群计算的容错性抽象方法
  • 原文地址:https://www.cnblogs.com/learnjfm/p/6936976.html
Copyright © 2011-2022 走看看