Session案例

SecondDream_1017發表於2018-08-15

原出處:https://www.cnblogs.com/HigginCui/p/5998431.html

【購物車中的資訊儲存】

【Book.java】

 

package com.Higgin.shopping;

public class Book {
    private String id;
    private String name;
    private String author;
    private double price;
    
    public Book(String id, String name, String author, double price) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.price = price;
    }
    
    //忽略get/Set方法
}

【Db.java】  模擬資料庫

 

package com.Higgin.shopping;

import java.util.LinkedHashMap;
import java.util.Map;

import org.junit.Test;

/**
 *  模擬一個儲存Book的資料庫 
 */
public class Db {
    private static Map<String,Book> map=new LinkedHashMap<String,Book>();
    
    static{
        map.put("1", new Book("1","《spring實戰》","沃爾斯 (Craig Walls)",66));
        map.put("2", new Book("2","《大型分散式網站架構設計與實踐》","陳康賢",79));
        map.put("3", new Book("3","《一線架構師實踐指南》","溫昱",35));
        map.put("4", new Book("4","《高效能網站構建實戰》","劉鑫",88));
        map.put("5", new Book("5","《淘寶技術這十年》","子柳",45));
    }
    
    public static Map getAll(){
        return map;
    }
    
    
    @Test
    public void test(){
        Map<String,Book> map=Db.getAll();  //獲取模擬資料庫Db的所有Book資料
        for(Map.Entry<String, Book> entry:map.entrySet()){
            Book book=entry.getValue();
            System.out.println(book.getName()+"<a href='BuyServlet?id="+book.getId()+"' target='_blank' >購買</a><br/>");
        }
    }
}

 

【ListBookServlet.java】 商品列表購買頁面

 

package com.Higgin.shopping;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 購買頁面
 * 模擬網站首頁  列出所有書本
 */
@WebServlet("/ListBookServlet")
public class ListBookServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public ListBookServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out =response.getWriter();
        
        out.println("本站有如下書籍:<br/>");
        Map<String,Book> map=Db.getAll();  //獲取模擬資料庫Db的所有Book資料
        for(Map.Entry<String, Book> entry:map.entrySet()){
            Book book=entry.getValue();
            //點選"購買"後跳轉至 BuyServlet處理,並帶上對應的書本Id
            out.print(book.getName()+"<a href='BuyServlet?id="+book.getId()+"' target='_blank' >購買</a><br/>");
        }
    }

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

}

 

【BuyServlet.java】 點選購買之後

 

package com.Higgin.shopping;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//點選購買
@WebServlet("/BuyServlet")
public class BuyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    public BuyServlet() {
        super();
    }

    //ListBookServlet點選購買後跳轉到這裡
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String id=request.getParameter("id"); //獲取書本的Id
        Book book=(Book) Db.getAll().get(id);  //根據Id查詢"資料庫"對應的書,即本次購買的書
        
        HttpSession session=request.getSession();
        
        //從Session得到使用者用於儲存所有書的集合(購物車)
        List<Book> list = (List) session.getAttribute("listBook");  //首次購買這裡沒有資料
        if(list==null){   //如果是首次購買
            list=new ArrayList();  //新建一個List
            session.setAttribute("listBook", list);  //將購買的書本放入Session
        }
        list.add(book);   //每多購買一本,就在List中多新增一本書
        //request.getRequestDispatcher("/ListCarServlet").forward(request, response);  //轉發會導致頁面在重新整理時,不斷購買剛剛購買的商品
        response.sendRedirect(request.getContextPath()+"/ListCarServlet");  //重定向:可以避免重新整理時重複購買的情況
    }

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

}

 

【ListCarServlet.java】  購物車頁面(點選購買了多少書本,就展示多少書本)

 

package com.Higgin.shopping;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 模擬購物車的頁面展示
 */
@WebServlet("/ListCarServlet")
public class ListCarServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public ListCarServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out =response.getWriter();
        
        HttpSession session =request.getSession(false); //獲取Session
        if(session==null){  //如果Session中為空
            out.write("您沒有購買任何商品!!!");
            return ;
        }
        
        out.write("您購買了如下商品:<br/>");
        List<Book> list=(List) session.getAttribute("listBook");  //如果Session不為空,提取對應的Session中的資料
        for(Book book:list){
            out.write(book.getName()+"<br/>");   //將提取的資料進行展示
        }
    }

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

}

【執行結果】

[1. 進入 http://localhost:8080/HelloServlet/ListBookServlet]

[2.點選購買]

[ 3.再點 ]

相關文章