zoukankan      html  css  js  c++  java
  • 尚硅谷ajax视频教程2

    7、7. 尚硅谷_佟刚_Ajax_典型应用_验证用户名是否可用

    整个项目的目录路径如下所示

    我们首先新建立一个web工程,在webroot下面新建立一个script的文件夹,导入jquer文件

    接下来我们编写index.jsp文件,通过ajax的方式校验该用户名是否在后台已经被注册

    index.jsp文件内容如下所示:

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
       
       <!-- 第一步导入jquery文件夹 -->
       <script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-2.1.1.js"></script>
       <script type="text/javascript">
       //第二步:
    
           
          //第二步:
            $(function(){
                //选择所有 <input> 元素:$(":input")
                //第二步获得name=username的结点
                //第三步为username添加change事件
                $("input[name='username']").change(function (){
    
                    //第四步获得username 对应的value的值,去掉前后空格,准备发送ajax
                    //$(this)是一个JQuery对象,this是当前的dom元素对象,使用$()可以将dom对象转化成jquery对象,这里就可以调用jquery的方法
                    var value= $(this).val();
                    //去掉前后的空格$.trim(str)的作用是去掉字符串首尾空格
                    value = $.trim(value);
                    alert(value);
                    if(value != ""){
                     //发送post请求
                     //请求的ur地址 UserNameServlet对应的是一个Servlet
                     var href="${pageContext.request.contextPath}/UserNameServlet";
                     //请求的提交给服务器的参数,参数必须满足json的字符串格式
                     var args={"username":value,"time":new Date()};
                     //result是客户端返回的结果
                     $.post(href,args,function(result){
                    
                         //返回的是一个html片段<font color="red">该用户名已经被注册</font>
                         // 我们要将该结果嵌入到id=message的div标签中:<div id="message"><font color="red">该用户名已经被注册</font></div>
                         $("#message").html(result);
                     });
                     
                    }    
                });
                
                
            })
            
    
       </script>
      </head>
      
      <body>
       <h2>查询用户名是否被注册</h2></br>
       <!-- 首先需要建立一个表单 -->
       <form action="" method="post" >
       <input type="text" name="username" />
       <input type="submit"  valeu="submit"/>
       </br>
       <div id="message"></div>
       </form>
      </body>
    </html>

    在后台我们编写一个servlet用于处理客户端的请求

    package com.weiyuan.test;
    
    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 UserNameServlet extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public UserNameServlet() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            this.doPost(request, response);
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
              request.setCharacterEncoding("utf-8");
              response.setCharacterEncoding("utf-8");
            //首先获得客户端请求过来传递的参数
            String username = request.getParameter("username");
            System.out.println("username :"+username);
            String result = "";
            if(username != null){
                if("aaa".equalsIgnoreCase(username) || "bbb".equalsIgnoreCase(username)){
                    result= "<font color='red'>该用户名已经被注册</font";
                }else{
                    result= "<font color='green'>该用户名可以正常使用</font";
                }
                //设置服务器返回的数据是html文件
              response.setContentType("text/html");
              //将数据返回回去
              response.getWriter().write(result);
            }
        }
    
        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occurs
         */
        public void init() throws ServletException {
            // Put your code here
        }
    
    }

    该servlet需要在web.xml中配置映射路径,web.xml配置文件如下所示

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>TestAjax</display-name>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>UserNameServlet</servlet-name>
        <servlet-class>com.weiyuan.test.UserNameServlet</servlet-class>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>UserNameServlet</servlet-name>
        <url-pattern>/UserNameServlet</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    我们来看看程序运行的效果

    相当的经典。

     8、8. 尚硅谷_佟刚_Ajax_典型应用_添加商品

    现在我们要实现购物车中,当用户点击某条购物项的时候,页面不发生跳转能够自动的发生变化

    当点击某个菜单项的数据的增删的时候总的书的数量和总价会自动的发生变化,我们采用ajax的方式来实现,页面不发生跳转

    这里主要是后台实现比较复杂

    这里的页面是由每一个购物车的菜单项构成的,由多个菜单项。一个菜单项应该包括:当前购买书的类型,当前购买的数量,以及当前购买书数量的价格

    然后遍历每个菜单项就可以获得当前购物车总的数量和价格了

    我们首先定义一个商品的实体类

    package cn.itcast.shop.product.beans;
    
    import java.util.Date;
    
    
    
    
    /**
     * 商品的实体对象
     * @author 传智.郭嘉
     *
     */
    public class Product {
        private Integer pid;
        //商品的名称
        private String pname;
        //商品的市场价格
        private Double market_price;
        //商品的现场价格
        private Double shop_price;
        //商品的图片地址
        private String image;
        //商品的具体描述
        private String pdesc;
        //是否是热门商品
        private Integer is_hot;
        //商品的上传日期
        private Date pdate;
      
    
        public Integer getPid() {
            return pid;
        }
        public void setPid(Integer pid) {
            this.pid = pid;
        }
        public String getPname() {
            return pname;
        }
        public void setPname(String pname) {
            this.pname = pname;
        }
        public Double getMarket_price() {
            return market_price;
        }
        public void setMarket_price(Double market_price) {
            this.market_price = market_price;
        }
        public Double getShop_price() {
            return shop_price;
        }
        public void setShop_price(Double shop_price) {
            this.shop_price = shop_price;
        }
        public String getImage() {
            return image;
        }
        public void setImage(String image) {
            this.image = image;
        }
        public String getPdesc() {
            return pdesc;
        }
        public void setPdesc(String pdesc) {
            this.pdesc = pdesc;
        }
        public Integer getIs_hot() {
            return is_hot;
        }
        public void setIs_hot(Integer is_hot) {
            this.is_hot = is_hot;
        }
        public Date getPdate() {
            return pdate;
        }
        public void setPdate(Date pdate) {
            this.pdate = pdate;
        }
    
        
    }

    第二步我们新建立一个购物车的菜单项,里面包括弄购物的商品,购买当前商品的数量,购物车由多个购物项构成

    package cn.itcast.shop.cart.beans;
    
    import cn.itcast.shop.product.beans.Product;
    
    /**
     * 购物项对象
     * @author 传智.郭嘉
     *
     */
    public class CartItem {
        private Product product;    // 购物项中商品信息
        private int count;            // 购买某种商品数量
        private double subtotal;    // 购买某种商品小计
        public Product getProduct() {
            return product;
        }
        public void setProduct(Product product) {
            this.product = product;
        }
        public int getCount() {
            return count;
        }
        public void setCount(int count) {
            this.count = count;
        }
        // 小计自动计算的.
        public double getSubtotal() {
            return count * product.getShop_price();
        }
        /*public void setSubtotal(double subtotal) {
            this.subtotal = subtotal;
        }
        */
        
    }

    第三步:我们封装购物车对象,对购物车进行操作包括购物车的增删改查操作

    package cn.itcast.shop.cart.beans;
    
    import java.io.Serializable;
    import java.util.Collection;
    import java.util.LinkedHashMap;
    import java.util.Map;
    
    /**
     * 购物车对象
     * 
     * @author 传智.郭嘉
     * 
     */
    public class Cart implements Serializable{
        // 购物车属性
        // 购物项集合:Map的key就是商品pid,value:购物项
        private Map<Integer, CartItem> map = new LinkedHashMap<Integer, CartItem>();
    
        // Cart对象中有一个叫cartItems属性.
        public Collection<CartItem> getCartItems(){
            return map.values();
        }
        
        // 购物总计:
        private double total;
    
        public double getTotal() {
            return total;
        }
    
        // 购物车的功能:
        // 1.将购物项添加到购物车
        public void addCart(CartItem cartItem) {
            // 判断购物车中是否已经存在该购物项:
            /*
             *  * 如果存在:
             *      * 数量增加
             *      * 总计 = 总计 + 购物项小计
             *  * 如果不存在:
             *      * 向map中添加购物项
             *      * 总计 = 总计 + 购物项小计
             */
            // 获得商品id.
            Integer pid = cartItem.getProduct().getPid();
            // 判断购物车中是否已经存在该购物项:
            if(map.containsKey(pid)){
                // 存在
                CartItem _cartItem = map.get(pid);// 获得购物车中原来的购物项
                _cartItem.setCount(_cartItem.getCount()+cartItem.getCount());
            }else{
                // 不存在
                map.put(pid, cartItem);
            }
            // 设置总计的值
            total += cartItem.getSubtotal();
        }
    
        // 2.从购物车移除购物项
        public void removeCart(Integer pid) {
            // 将购物项移除购物车:
            CartItem cartItem = map.remove(pid);
            // 总计 = 总计 -移除的购物项小计:
            total -= cartItem.getSubtotal();
        }
    
        // 3.清空购物车
        public void clearCart() {
            // 将所有购物项清空
            map.clear();
            // 将总计设置为0
            total = 0;
        }
    }

    这里需要注意的是在购物车的Cart类中封装了一个方法

      // Cart对象中有一个叫cartItems属性.
        public Collection<CartItem> getCartItems(){
            return map.values();
        }

    将购物车的购物项封装成一个set集合,这样在jsp页面的时候就可以对cartItems集合进行遍历,相当于在Cart类之后定义一个cartItems成员变量,提供了外界可以访问的get方法

    如下图片所示

    现在我们写一个简单的页面,通过ajax模拟下面的操作获得对应总的数量和操作

    package com.weiyuan.test;
    
    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;
    
    import cn.itcast.shop.cart.beans.Cart;
    import cn.itcast.shop.cart.beans.CartItem;
    import cn.itcast.shop.product.beans.Product;
    
    public class ProductServlet extends HttpServlet {
    
        /**
         * Constructor of the object.
         */
        public ProductServlet() {
            super();
        }
    
        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }
    
    
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
         
            this.doPost(request, response);
        }
    
        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
             //默认都是添加操作
            //首先获得你添加进来的商品的id和商品的价格
            String product_id = request.getParameter("product_id");
            String product_proce = request.getParameter("product_price");
            System.out.println("product_id:"+product_id);
            System.out.println("product_price"+product_proce);
            //将字符串转化成id类型
            int id = Integer.parseInt(product_id);
            Double shop_price = Double.parseDouble(product_proce);
            Product product = new Product();
            if(id == 1){
                //说明是java对象
                
                product.setPid(1);
                product.setPname("java");
                product.setShop_price(shop_price);
                
            }
            if(id == 2){
                //说明是mysql对象
                product.setPid(2);
                product.setPname("mysql");
                product.setShop_price(shop_price);
            }
            //创建一个购物车菜单项将购物车添加到菜单项中
            CartItem cartItem = new CartItem();
            cartItem.setProduct(product);
            //默认每次都是购买一本
            cartItem.setCount(1);
            
            //然后获得购物车
             Cart cart = (Cart) request.getSession().getAttribute("cart");
                if (cart == null) {
                    cart = new Cart();
                    request.getSession().setAttribute("cart", cart);
                }
             //cartItem添加到购物车中
              cart.addCart(cartItem);
              
              //获得购物车中总的购买的商品和价格返回给客户端
              //我们采用字符串
            
        }
    
        /**
         * 获得购物车的方法:从session中获得购物车.
         * @return
         */
        private Cart getCart() {
           
            return cart;
    
    }
  • 相关阅读:
    Oracle求连续的年份
    关于Extjs MVC模式上传文件的简单方式
    后进先出 stack、 先进先出Queue
    python的文件操作
    C#的接口
    C#的访问级别
    C#的继承
    SQL查询语句 常用示例
    SQL Server数据库常用函数
    数据库建立和连接
  • 原文地址:https://www.cnblogs.com/kebibuluan/p/8886844.html
Copyright © 2011-2022 走看看