Ajax案例:简易的购书网页

Posted G-&-D

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax案例:简易的购书网页相关的知识,希望对你有一定的参考价值。

****使用Ajax可以不需要刷新整个页面,而使局部页面更新的技术;

****JSON是javascript得原生格式,JavaScript中处理JSON数据不需要特殊的工具或架包,其规则很简单,对象就是一个为序的“名称/值”对的集合,但是在servlet类中书写时比较麻烦。

       所以导入Jackson的两个开源架包:jackson-core-asl-1.9.11.jar,jackson-mapper-asl-1.9.11.jar;其中有个类ObjectMapper,可以简化JSON在servlet类中书写的繁琐;

ObjectMapper mapper=new ObjectMapper();
String result=mapper.writeValueAsString(sc);

 

建立一个ShoppingCarItam类,封装了书的一些属性:如bookName,bookNum,price;

package com.lanqiao.javaweb.beans;

public class ShoppingCarItam {
    private int bookNum;//书的个数
    private String bookName;//书的名字
    private double price;
    
    public ShoppingCarItam() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ShoppingCarItam(int bookNum, String bookName, double price) {
        super();
        this.bookNum = bookNum;
        this.bookName = bookName;
        this.price = price;
    }

    public int getBookNum() {
        return bookNum;
    }

    public void setBookNum(int bookNum) {
        this.bookNum = bookNum;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "ShoppingCarItam [bookNum=" + bookNum + ", bookName=" + bookName + ", price=" + price + "]";
    }
    
    
}

 

建一个ShoppingCart类,里面有一些常用方法,添加书的数目,书名,数的价格的方法addToCart()...,尤其有三个get方法,便于ObjectMapper类获取,其方法名和值;将其放在map集合中,string为书名;

package com.lanqiao.javaweb.beans;

import java.util.HashMap;
import java.util.Map;

public class ShoppingCart {
    //存放shoppingcaritem的map:键:书名,值:shoppingcatitem对象
    private Map<String, ShoppingCarItam> items=new HashMap<String,ShoppingCarItam>();
    
    private String bookName;
    
    ShoppingCarItam item=null;
    public void addToCart(String bookName,double price){
        this.bookName=bookName;
        //如果集合中已经有该书了,获取其书名,直接将其数量加1
        if(items.containsKey(bookName)){
            item=items.get(bookName);
            item.setBookNum(item.getBookNum() +1);
            
        }
        else{
            //如果集合中没有该书,设置该书的书名,价格,数量加1;
            item=new ShoppingCarItam();
            
            item.setBookName(bookName);
            item.setPrice(price);
            item.setBookNum(1);
            items.put(bookName, item);
        }
    }
    
    //获取书的总数量
    public int getTotalBookNum(){
        int total=0;
        for(ShoppingCarItam item1:items.values()){
            total+=item1.getBookNum();
        }
        return total;
    }
    //获取书名
    public String getBookName() {
        return bookName;
    }
    
    //总的价格
    public double getTotalMoney(){
        double money=0.0;
        for(ShoppingCarItam item2:items.values()){
            money+=item2.getPrice()*item2.getBookNum();
        }
        return money;
    }
}

 

建立一个Servlet类:AddToCartServlet,可以获取index.jsp中的书名id,price,然后调用ShoppingCart类中的方法,得出中的书的数量,总的金额,通过ObjectMapper类,获取ShoppingCart类中的get方法,并获取该方法的值。。。

package com.lanqiao.javaweb.beans;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

public class AddToCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求的参数id(bookName),price
        String bookName=request.getParameter("id");
        double price=Double.parseDouble(request.getParameter("price"));
        
        //获取购物车对象
        HttpSession session=request.getSession();
        ShoppingCart sc=(ShoppingCart)session.getAttribute("sc");
        
        if (sc==null) {
            sc=new ShoppingCart();
            session.setAttribute("sc", sc);
        }
        
        //把点击选项加入购物车
        sc.addToCart(bookName, price);
        
        //准备相应的JSON对象
//        StringBuilder result=new StringBuilder();
//        result.append("{")
//              .append("\"bookName\":\""+bookName+"\"")
//              .append(",")
//              .append("\"totalBookNum\":\""+sc.getTotalBookNum()+"\"")
//              .append(",")
//              .append("\"totalMoney\":\""+sc.getTotalMoney()+"\"")
//              .append("}");
        
        //导入Jackson的两个开源架包,可以简化JSON代码,如上为JSON 的代码,比较繁琐
        //ObjectMapper类可以获取get方法的方法名和其返回值,以名称/值,对的方式输出;
        ObjectMapper mapper=new ObjectMapper();
        String result=mapper.writeValueAsString(sc);
        System.out.println(result);
        
        //响应JSON对象
        response.setContentType("text/javascript");
        response.getWriter().print(result);
        //response.getWriter().println(result.toString());
    }

}

 

index.jsp页面:使用了Ajax的$.getJSON

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
    $(function(){
        //隐藏div
        var isHasCart="${sessionScope.sc==null}";
        //alert(isHasCart);
        if (isHasCart=="true") {
            $("#cart").hide();
        }else{
            $("#cart").show();
            $("#bookName").text("${sessionScope.sc.bookName}");
            $("#totalBookNum").text("${sessionScope.sc.totalBookNum}");
            $("#totalMoney").text("${sessionScope.sc.totalMoney}");
        }
        //未点击时div是隐藏的
        $("a").click(function() {
            //未点击时div是隐藏的
            $("#cart").show();
            
      //获取url地址 var url
=this.href;
      //时间拽,阻止缓存 var args
={"time":new Date()};
        //getJSON方法 $.getJSON(url,args,function(data){ $(
"#bookName").text(data.bookName); $("#totalBookNum").text(data.totalBookNum); $("#totalMoney").text(data.totalMoney); }); return false; }); }) </script> </head> <body> <div id="cart"> 您已经将&nbsp;<span id="bookName"></span>&nbsp;加入购物车 购物车中有&nbsp;<span id="totalBookNum"></span>&nbsp;本书 总价格为&nbsp;<span id="totalMoney"></span>&nbsp; </div> <br><br> <!--pageContext.request.contextPath为绝对路径,相对而言较为安全 --> java&nbsp;&nbsp;<a href="${pageContext.request.contextPath }/addToCart?id=java&price=200">加入购物车</a> <br><br> Oracle&nbsp;&nbsp;<a href="${pageContext.request.contextPath }/addToCart?id=Oracle&price=150">加入购物车</a> <br><br> Structs2&nbsp;&nbsp;<a href="${pageContext.request.contextPath }/addToCart?id=Structs2&price=100">加入购物车</a> <br><br> </body> </html>

 

lib下的web.xml文件

<servlet>
<description></description>
<display-name>AddToCart</display-name>
<servlet-name>AddToCart</servlet-name>
<servlet-class>com.lanqiao.javaweb.beans.AddToCartServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddToCart</servlet-name>
<url-pattern>/addToCart</url-pattern>
</servlet-mapping>

 

以上是关于Ajax案例:简易的购书网页的主要内容,如果未能解决你的问题,请参考以下文章

免费下载全套最新004JavaWEB购书系统视频教程+教学资料+学习课件+源代码+软件开发工具

Java课程案例学习

DOM操作相关案例 模态对话框,简易留言板,js模拟选择器hover,tab选项卡,购物车案例

AjaxJSON学习笔记

Ajax 使用ajax加上get和post方法,通过后台加载数据,并在网页上进行显示案例+解释

Ajax网页爬取案例详解