package session.test;

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

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

//代表网站,列出所有书籍
public class SessionDemo1 extends HttpServlet {

public 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.write("本网站有如下书籍:<br/>");
        Map<String,Book> map = Db.getAll();
        for(Map.Entry<String,Book>entry:map.entrySet()) {
            Book book = entry.getValue();
            out.println("<a href='/session/servlet/SessionDemo2?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>");
           
        }
       
        //2,显示用户看过的商品
        out.print("<br/>您曾经浏览过的商品:<br/>");
        HttpSession session= request.getSession(false);
        if(session==null) {
            out.write("尚未购买商品<br/>");
            return;
        }
        out.write("购物车中商品:<br/>");
        List<String> list = (List)session.getAttribute("list");
        for(String str:list) {
            out.write(str+"<br/>");
        }
    }

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

}

}

class Db{
    //private Map map = new HashMap();
    private static Map<String,Book> map = new LinkedHashMap<String,Book>();
    static {
        map.put("1",new Book("1","水浒传","施耐庵","名著"));
        map.put("2",new Book("2","三国演义","罗贯中","名著"));
        map.put("3",new Book("3","西游记","吴承恩","名著"));
        map.put("4",new Book("4","红楼梦","曹雪芹","名著"));
        map.put("5",new Book("5","金-瓶梅","笑笑生","名著"));
    }
   
    public static Map<String, Book> getAll() {
        return map;
    }
}

class Book{
    private String id;
    private String name;
    private String author;
    private String description;
   
   
    public Book() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Book(String id, String name, String author, String description) {
        super();
        this.id = id;
        this.name = name;
        this.author = author;
        this.description = description;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }

}

package session.test;

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

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//购买servlet
public class SessionDemo2 extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html);charset=UTF-8");
        PrintWriter out = response.getWriter();

//根据用户带过来的id,显示相应商品的详细信息
        String id = request.getParameter("id");
        Book book = (Book)Db.getAll().get(id);
        out.write(book.getId() + "<br/>");
        out.write(book.getName() + "<br/>");
        out.print(book.getAuthor() + "<br/>");/////////////////////////////
        out.write(book.getDescription() + "<br/>");
       
        //构建session
       
        HttpSession session = request.getSession();
        //用集合来保存买的东西。
        List list = (List) session.getAttribute("list");
        if(list==null) {
            list = new ArrayList();
            session.setAttribute("list", list);
        }
           
        list.add(book);
        //session.setAttribute("list", list);

//        request.getRequestDispatcher("/servlet/SessionDemo1").forward(request, response);
//        this.getServletContext().getRequestDispatcher("/servlet/SessionDemo1").forward(request, response);
        response.sendRedirect(request.getContextPath()+"/servlet/SessionDemo3");//
    }

private String buildSession(String id, HttpServletRequest request) {

//bookHistory = null
       
        String bookHistory = null;
        Cookie cookies[] = request.getCookies();
        for(int i=0;cookies!=null&&i<cookies.length;i++) {
            if(cookies[i].getName().equals("bookHistory"));
                bookHistory = cookies[i].getValue();
               
        }
       
        if(bookHistory==null) {
            return id;
        }
       
        LinkedList<String> list = new LinkedList<String>(Arrays.asList(bookHistory.split("\\,")));
        if(list.contains(id)) {
            list.remove(id);
           
        }else {
            if(list.size()>=3) {
                list.removeLast();
            }
        }
        list.addFirst(id);
       
        StringBuffer sb = new StringBuffer();
        for(String bid : list) {
            sb.append(bid + ",");
        }
        return sb.deleteCharAt(sb.length()-1).toString();
    }

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

}

}

package session.test;

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

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

public class SessionDemo3 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.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write("<br/>");
        out.write("<br/>");
       
        //2,显示用户看过的商品
        out.print("<br/>您曾经浏览过的商品:<br/>");
        HttpSession session= request.getSession(false);
        if(session==null) {
            out.write("尚未购买商品<br/>");
            return;
        }
        out.write("购物车中商品:<br/>");
        List list = (List)session.getAttribute("list");
        for(Object str:list) {
            Book book = (Book)str;
            out.write(book.getName()+"<br/>");
        }
       
    }

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

}

}

客户端无法存cookie的情况,把sessionID存到地址栏。

request.getSession();//先创建session不然下面这句不会有效果

……

String url = response.encodeRedirectUrl(url);

对于重定向的url:

String url = response.encodeRedirectURL(……);

session Id存在地址栏,如果客户端支持cookie会自动存在cookie里,否则才会存在地址栏

Session 简单购物车的更多相关文章

  1. Session小案例-----简单购物车的使用

    Session小案例-----简单购物车的使用 同上篇一样,这里的处理请求和页面显示相同用的都是servlet. 功能实现例如以下: 1,显示站点的全部商品 2.用户点击购买后,可以记住用户选择的商品 ...

  2. java:Session(概述,三层架构实例(实现接口封装JDBC),Session实现简单购物车实例)

    1.Session概述: Session:在计算机中,尤其是在网络应用中,称为“会话控制”.Session 对象存储特定用户会话所需的属性及配置信息.这样,当用户在应用程序的 Web 页之间跳转时,存 ...

  3. Session简单介绍

    Session 会话 , Session是基于Cookie的一种会话机制. Cookie是服务器返回一小份数据给客户端,并且存放在客户端上. Session是,数据存放在服务器端. 常用API //得 ...

  4. 简单购物车程序(Python)

    #简单购物车程序:money_all=0tag=Trueshop_car=[]shop_info={'apple':10,'tesla':100000,'mac':3000,'lenovo':3000 ...

  5. python实现简单购物车系统(练习)

    #!Anaconda/anaconda/python #coding: utf-8 #列表练习,实现简单购物车系统 product_lists = [('iphone',5000), ('comput ...

  6. JavaWeb学习总结(十):Session简单使用

    一.Session简单介绍 在WEB开发中,服务器可以为每个用户浏览器创建一个会话对象(session对象),注意:一个浏览器独占一个session对象(默认情况下).因此,在需要保存用户数据时,服务 ...

  7. Python实例---简单购物车Demo

    简单购物车Demo # version: python3.2.5 # author: 'FTL1012' # time: 2017/12/7 09:16 product_list = ( ['Java ...

  8. 用Python实现简单购物车

    作业二:简单购物车# 实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,# 如果输入为空或其他非法输入则要求用户重新输入 shopping_list = [] w ...

  9. 会话技术之Session(购物车加入、查看和清空)

    会话技术之Session session:服务器端会话技术 当我们第一次访问的服务器的时候,服务器获取id, 能获取id 要拿着这个id去服务器中查找有无此session 若查找到了:直接拿过来将数据 ...

随机推荐

  1. noip模拟 五子棋

    递推+模拟.在读取数据时,我们建4个图,分别代表这个图中横.纵.左斜右斜的连续长度.例如heng[i][j]代表ij这个点所在的横着一条线的长度. 然后搜索,对于一个空点,如果他的上下都>=4那 ...

  2. Java高级架构师(一)第41节:Nginx的配置优化以及使用建议

  3. Codeforces Round #348 (VK Cup 2016 Round 2, Div. 2 Edition) C. Little Artem and Matrix 模拟

    C. Little Artem and Matrix 题目连接: http://www.codeforces.com/contest/669/problem/C Description Little ...

  4. HDU 4611 Balls Rearrangement 数学

    Balls Rearrangement 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=4611 Description Bob has N balls ...

  5. 查看linux启动的线程信息

    1.某一进程所有的线程个数.启动时间 ps max -o lstart,lwp,pid,nlwp,cmd|more lstart:     STARTED time the command start ...

  6. 关于orcad元件库

    ORCAD CAPTURE 零件库解析 ORCAD CAPTURE 零件库解析 1' AMPLIFIER.OLB 共182个零件,存放模拟放大器IC,如CA3280,TL027C,EL4093等. 2 ...

  7. Upgrading Directly from MySQL 5.0 to 5.7 using an ‘In Place’ Upgrade

    http://mysqlserverteam.com/upgrading-directly-from-mysql-5-0-to-5-7-using-an-in-place-upgrade/

  8. 海思hi3518 opencv测试

    2.4.9的opencv 安装好交叉编译后,用Cmake 配置opencv 修改CMakeCache.txtCMAKE_EXE_LINKER_FLAGS:STRING=-lpthread -lrt - ...

  9. 用10张图来看机器学习Machine learning in 10 pictures

    I find myself coming back to the same few pictures when explaining basic machine learning concepts. ...

  10. Orchard运用 - 学习资源分享

    这段时间研究Orchard,看到一些资源十分有用. 比如国内还是有些牛人在分享心得,在此也广播一下给新手: JustRun对Orchard的一些代码分析 Orchard源码分析 Orchard中文社区 ...