The use of Ajax can not need to refresh the entire page, and make the local page update technology;
JSON is a native format for JavaScript, which does not require special tools or racks for working with JSON data, and the rules are simple: An object is a collection of ordered name/value pairs, but it is cumbersome to write in a servlet class.
So into Jackson's two open-source rack package: Jackson-core-asl-1.9.11.jar,jackson-mapper-asl-1.9.11.jar; there's a class objectmapper, It can simplify the tedious writing of JSON in the Servlet class;
Objectmapper mapper=new objectmapper ();
String Result=mapper.writevalueasstring (SC);
Create a Shoppingcaritam class that encapsulates some of the properties of a book: such as Bookname,booknum,price;
PackageCom.lanqiao.javaweb.beans; Public classShoppingcaritam {Private intBooknum;//Number of Books PrivateString BookName;//the name of the book Private DoublePrice ; PublicShoppingcaritam () {Super(); //TODO auto-generated Constructor stub } PublicShoppingcaritam (intBooknum, String BookName,DoublePrice ) { Super(); This. Booknum =Booknum; This. BookName =BookName; This. Price =Price ; } Public intGetbooknum () {returnBooknum; } Public voidSetbooknum (intbooknum) { This. Booknum =Booknum; } PublicString Getbookname () {returnBookName; } Public voidsetbookname (String bookname) { This. BookName =BookName; } Public DoubleGetPrice () {returnPrice ; } Public voidSetprice (DoublePrice ) { This. Price =Price ; } @Override PublicString toString () {return"Shoppingcaritam [booknum=" + Booknum + ", bookname=" + BookName + ", price=" + Price + "]"; } }
Build a ShoppingCart class, there are some common methods, add the number of books, the title, the number of the price of the method AddToCart () ..., in particular, there are three get methods to facilitate the Objectmapper class to obtain, its method name and value; put it in the map collection, String is the title of the book;
PackageCom.lanqiao.javaweb.beans;ImportJava.util.HashMap;ImportJava.util.Map; Public classShoppingCart {//map for storing Shoppingcaritem: Key: Title, Value: Shoppingcatitem object PrivateMap<string, shoppingcaritam> items=NewHashmap<string,shoppingcaritam>(); PrivateString BookName; Shoppingcaritam Item=NULL; Public voidAddToCart (String BookName,DoublePrice ) { This. bookname=BookName; //If the book is already in the collection, get its title, and add the number 1 directly if(Items.containskey (bookname)) {Item=Items.get (bookname); Item.setbooknum (Item.getbooknum ()+1); } Else{ //if the book is not in the collection, set the book title, Price, quantity plus 1;item=NewShoppingcaritam (); Item.setbookname (BookName); Item.setprice (price); Item.setbooknum (1); Items.put (BookName, item); } } //get the total number of books Public intGettotalbooknum () {intTotal=0; for(Shoppingcaritam item1:items.values ()) { Total+=Item1.getbooknum (); } returnTotal ; } //get the title PublicString Getbookname () {returnBookName; } //the Total price Public DoubleGettotalmoney () {Doublemoney=0.0; for(Shoppingcaritam item2:items.values ()) { money+=item2.getprice () *Item2.getbooknum (); } returnMoney ; }}
Create a servlet class: Addtocartservlet, You can get the title Id,price in index.jsp, and then call the method in the ShoppingCart class to get the number of books in, the total amount, through the Objectmapper class, obtain the Get method in the ShoppingCart class, and get the value of the method ...
PackageCom.lanqiao.javaweb.beans;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;ImportOrg.codehaus.jackson.map.ObjectMapper; Public classAddtocartservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doPost (request, response); } protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//gets the parameter ID of the request (BookName), priceString bookname=request.getparameter ("id"); DoublePrice=double.parsedouble (Request.getparameter ("Price")); //Get Shopping Cart objectsHttpSession session=request.getsession (); ShoppingCart SC= (ShoppingCart) session.getattribute ("SC"); if(sc==NULL) {SC=NewShoppingCart (); Session.setattribute ("SC", SC); } //Add click option to CartSc.addtocart (BookName, Price); //prepare the appropriate JSON object//StringBuilder result=new StringBuilder ();//Result.append ("{")//. Append ("\" bookname\ ": \" "+bookname+" \ "")//. Append (",")//. Append ("\" totalbooknum\ ": \" "+sc.gettotalbooknum () +" \ ")//. Append (",")//. Append ("\" totalmoney\ ": \" "+sc.gettotalmoney () +" \ ")//. Append ("}"); //by importing Jackson's two open source rack packages, you can simplify the JSON code, such as the JSON-like code, which is more cumbersome//The Objectmapper class can get the method name of the Get method and its return value, output by name/value, in the same way;Objectmapper mapper=NewObjectmapper (); String result=Mapper.writevalueasstring (SC); SYSTEM.OUT.PRINTLN (result); //responding to JSON objectsResponse.setcontenttype ("Text/javascript"); Response.getwriter (). Print (result); //Response.getwriter (). println (Result.tostring ()); }}
index.jsp page: $.getjson with Ajax
<%@ 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" >$ (function () {//Hide Divvar 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 is hidden when not clicked$ ("a"). Click (function () {//Div is hidden when not clicked$ ("#cart"). Show ();
Get URL address var url= This. href;
Time drag to block cache var args={"Time":NewDate ()};
Getjson Method $.getjson (url,args,function (data) {$ ("#bookName"). Text (data.bookname); $("#totalBookNum"). Text (data.totalbooknum); $("#totalMoney"). Text (Data.totalmoney); }); return false; }); }) </script>you have <span id= "BookName" ></span> add to cart shopping cart <span id= "Totalbooknum" ></span> The total price of this book is <span id= "Totalmoney" ></span> </div> <br><br> <!--PageContext.request.contextPath is the absolute path, relatively safe--Java <a href= "${pagecontext.request.contextpath}/addtocart?id=java&price=200" > Add to Cart </a> <br><br>Oracle <a href= "${pagecontext.request.contextpath}/addtocart?id=oracle&price=150" > Add to Cart </a> <br><br>Structs2 <a href= "${pagecontext.request.contextpath}/addtocart?id=structs2&price=100" > Add to Cart </a> <br><br> </body>The Web. xml file under Lib
<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 case: Easy to buy book page