javaweb中servlet处理cookies+json

时间:2021-12-31 13:10:05
    
import  java.io.*;
import  java.util.*;
import  javax.servlet.*;
import  javax.servlet.http.*;
import  net.sf.json.JSONObject;
import  com.masque.beans.BookBean;
import  com.masque.daoimpl.BookDaoImpl;
import  com.sun.xml.internal.bind.v2.runtime.Name;
import  com.sun.xml.internal.bind.v2.runtime.output.Encoded;
     
/**
  * 此类描述的是对存储书籍的cookies的处理,再返回数据到jsp   
  */
public  class  BuyOneBook  extends  HttpServlet {
     /**
      * 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 {
         response.setContentType( "text/html,charset=UTF-8" );
         // 得到jsp传过来的书本的id
         int  bookId = Integer.parseInt((String) request.getParameter( "count" ));
         // 得到cookies数组
         request.setCharacterEncoding( "UTF-8" );
         Cookie[] cookie = request.getCookies();
         // 定义变量用来接受书本保存的json的字符串表现形式
         String bookList =  null ;
         //定义一个标志位判断书籍的json你时候有该书籍
         boolean  isIn =  false ;
         boolean  isNew =  true ;
         if  (cookie !=  null ) {
             // 遍历cookie数组
             for  ( int  i =  0 ; i < cookie.length; i++) {
                 if  (cookie[i].getName().equals( "jsonBookList" )) {
                     bookList = cookie[i].getValue();
                     bookList = java.net.URLDecoder.decode(bookList, "UTF-8" );
                     //bookList = new String(bookList.getBytes("ISO-8859-1"), "gbk");
                 }
             }
             System.out.println( "bookList:" +bookList);
             if  (bookList !=  null ) {
                 // 将字符串转换为json对象
                 JSONObject jsonBookList = JSONObject.fromObject(bookList);
                 // 获取json对象的迭代器
                 Iterator iterator = jsonBookList.keySet().iterator();
                 // 遍历迭代器,查询json中是否存在当前用户购买的书籍
                 while  (iterator.hasNext()) {
                     // 得到用户购买书籍的id
                     String key = iterator.next().toString();
                         // 判断是否已购买
                     if  (key.equals(bookId+ "" )) {
                         isIn =  true ;
                         break ;
                     }
                 }
                 if  (!isIn) {
                     //如果书籍没有被购买,初始化书籍的数量,再添加书籍到json
                     int  bookSize =  1 ;
                     //添加书籍到json
                     addBook(bookId, jsonBookList,response,bookSize);
                 } else  { //json存在该书籍,则给給书籍的数量加1
                     //已经被购买的书籍的json
                     JSONObject jsonBook = JSONObject.fromObject(jsonBookList.get(bookId+ "" ).toString());
                     int  bookSize = Integer.parseInt(jsonBook.get( "bookSize" ).toString())+ 1 ;
                     //添加书籍到json
                     addBook(bookId, jsonBookList,response,bookSize);
                 }
             } else  {
                 isNew =  false ;
             }
         } else  {
             isNew =  false ;
         }
         if  (!isNew) {
             //生成一个JSONObject对象
             String data =  "{}" ;
             JSONObject jsonBookList = JSONObject.fromObject(data);  
             //添加书籍到json
             int  bookSize =  1 ;
             addBook(bookId, jsonBookList,response,bookSize);
         }
         //跳转到处理cookies的servlet
         response.sendRedirect( "readallbook.do?load=1" );
     }
     
     /**
      * 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 {
         doGet(request, response);
     }
     
     private  void  addBook( int  bookId, JSONObject jsonBookList,HttpServletResponse response, int  bookSize) {
         // 定义集合保存一本书的信息
         Map<String, String> map =  new  HashMap<String, String>();
         // 根据书籍的id得到书籍实体对象
         BookBean bookBean = ( new  BookDaoImpl()).SelectOneBook(bookId);
         // 添加表格需要显示的书籍的信息添加到集合
         map.put( "bookId" , bookId +  "" );
         map.put( "title" , bookBean.getTitle());
         map.put( "price" , bookBean.getPrice() +  "" );
         map.put( "bookSize" , bookSize+ "" );
         map.put( "priceAll" , bookBean.getPriceAll()+ "" );
         //将该书籍的信息的集合添加到json对象中
         jsonBookList.put(bookId, map);
         //将json的字符串形式添加到cookies中
         String str= null ;
         try  {
             str = java.net.URLEncoder.encode(jsonBookList.toString().replace( "\"" "\'" ), "UTF-8" );
         catch  (UnsupportedEncodingException e1) {
             e1.printStackTrace();
         }
         Cookie  cookie =  new  Cookie( "jsonBookList" ,str);
         //cookie.setMaxAge(300);
         response.addCookie(cookie);
     }
     
}