16_会话技术_Session案例

Posted HigginCui

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了16_会话技术_Session案例相关的知识,希望对你有一定的参考价值。

【购物车中的信息保存】

【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.再点 ]

 

以上是关于16_会话技术_Session案例的主要内容,如果未能解决你的问题,请参考以下文章

php_会话技术 — session

03012_会话技术Cookie&Session

Cookie和Session_会话技术

如何通过 apache 清除 PHP $_SESSION?

在 AJAX 请求上为空 $_SESSION 超全局,但保留会话 ID

“未定义变量:_SESSION”VS。 “会话已经开始”