cookie机制采用的是在客户端保持状态的方案,而session机制采用的是在服务器端保持状态的方案;

由于采用服务器端保持状态的方案在客户端也需要保存一个标识,所以session机制可能需要借助于cookie机制来达到保存标识的目的。

session实现购物车案例

Book.java

javabean

package car;

public class Book {

    private String id;
private String bookName;
private String author;
private int price;
private String description;
private int count; public Book(String id, String bookName, String author, int price,
String description) {
this.id = id;
this.bookName = bookName;
this.author = author;
this.price = price;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "Book [id=" + id + ", bookName=" + bookName + ", author="
+ author + ", price=" + price + ", description=" + description + "]";
} }

BookUtils.java

用来存取数据

package utils;

import java.util.HashMap;
import java.util.Map; import car.Book; public class BookUtils { private static Map<String,Book> map = new HashMap<String,Book>(); static{
map.put("", new Book("","三年中考五年模拟","李刚",,"中学生的噩梦"));
map.put("", new Book("","最后一个硬汉","郎咸平",,"666的经济学"));
map.put("", new Book("","我的奋斗","李刚",,"中学生的噩梦"));
map.put("", new Book("","三年中考五年模拟444","李刚4",,"中学生的噩梦4"));
map.put("", new Book("","三年中考五年模拟555","5李刚",,"中学生的噩梦5"));
map.put("", new Book("","666三年中考五年模拟","李6刚",,"中学生的噩梦6"));
}
//获取所有的书
public static Map<String,Book> getAllBook(){
return map;
}
//根据书的id获取某一本书
public static Book getBookById(String id){
return map.get(id);
}
}

ShowAllBookServlet.java

显示所有的书籍信息,从map中拿取信息

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import utils.BookUtils;
import car.Book; public class ShowAllBookServlet extends HttpServlet { /**
* 1.显示所有书的信息
* 2.提供一个购物车的链接
* 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 { request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.write("书库:<br><br>");
//1.显示所有的书
Map<String, Book> map = BookUtils.getAllBook();
//显示获取到的书
for (Map.Entry<String, Book> entry : map.entrySet()) {
//拿到每一本的id
String id = entry.getKey();
//拿到每一本书
Book book = entry.getValue();
//输出书的内容
out.write(" 《 " + book.getBookName() +" 》 " +"<a href=' "+ request.getContextPath() +"/servlet/ShowBookDetailServlet?id=" + id + " '>显示详细信息<a><br><br>");
}
out.write("<br><hr>");
//提供查看购物车的链接
out.write("<a href=' " + request.getContextPath() + "/servlet/CarServlet '>查看购物车</a>"); } /**
* 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);
} }

ShowBookDetailServlet.java

显示书籍的详细信息,并可以将书籍加入购物车

package servlet;

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import utils.BookUtils;
import car.Book; public class ShowBookDetailServlet extends HttpServlet { /**
* 1.显示书的详细信息
* 2.提供购物车的链接
* 3.返回继续浏览的链接
* 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 { request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); //显示书的详细信息
String id = request.getParameter("id");
Book book = BookUtils.getBookById(id); out.write(book + "<a href=' " + request.getContextPath() + "/servlet/ShowAllBookServlet '> 返回主页继续浏览 </a>" + "&nbsp;&nbsp;<a href=' " + request.getContextPath() + "/servlet/BuyServlet?id=" + id + " '>放入购物车</a>"); } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doGet(request, response);
} }

BuyServlet.java

处理提交的数据,将数据放入session中

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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; import utils.BookUtils;
import car.Book; public class BuyServlet 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 { request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter(); //获取页面传递的id
String id = request.getParameter("id");
//根据id找到对象
Book book = BookUtils.getBookById(id);
//将书存入session中
HttpSession session = request.getSession();
//将书放到session的一个集合中
List<Book> list = (List<Book>) session.getAttribute("carlist"); if(list == null){
//说明是第一次加入购物车
list = new ArrayList<Book>();
//将·书放入
book.setCount();
list.add(book);
//将list放入session
session.setAttribute("carlist", list);
}else{
//说明购物车已经有了东西了
//判断是否购买过书了
int index = list.indexOf(book);
if(index == -){
//没有
book.setCount();
list.add(book);
}else{
//说明已经买过一次了
Book b = list.get(index);
b.setCount(b.getCount() + );
}
//提醒用户,书已经放入了
out.write(book.getBookName() + "已经加入购物车,4秒后转向主页 <a href=' " + request.getContextPath() + "/servlet/ShowAllBookServlet '>回到主页</a>");
response.setHeader("Refresh", "4;url=" + request.getContextPath() + "/servlet/ShowAllBookServlet");
} } /**
* 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);
} }

CarServlet.java  存放购物车的信息

package servlet;

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; import car.Book; public class CarServlet 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 { request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter(); out.write("欢迎来到购物车<br>"); HttpSession session = request.getSession();
if(session.isNew()){
//直接返回主页面
response.sendRedirect(request.getContextPath() + "/servlet/ShowAllBookServlet");
return;
} //先从session拿到购物车
List<Book> list = (List<Book>) session.getAttribute("carlist");
//如果直接过来的,则让他回去
if(list == null){
//首次访问
out.write("您还没有购买任何东西,2秒后返回主页");
response.setHeader("Refresh", "2;url=" + request.getContextPath() + "/servlet/ShowAllBookServlet");
return;
}
//说明有数
out.write("您购买的书籍如下:<br>");
out.write("书名\t数量\t总价格<br>");
for (int i = ; i< list.size(); i++) {
Book b = list.get(i);
out.write(b.getBookName() + "\t" + b.getCount() + "\t" + b.getPrice() * b.getCount() + "<br>");
}
out.write("<br><br><a href=' " + request.getContextPath() + "/servlet/ShowAllBookServlet '>返回主页</a>"); } /**
* 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);
} }

可以了。

session原理解析的更多相关文章

  1. Spring Session原理解析

    前景提要: @EnableRedisHttpSession导入RedisHttpSessionConfiguration.classⅠ.被RedisHttpSessionConfiguration继承 ...

  2. 从session原理出发解决微信小程序的登陆问题

    声明:本文为作者原创文章,转载请注明出处 https://www.cnblogs.com/MaMaNongNong/p/9127416.html  原理知识准备  对于已经熟悉了session原理的同 ...

  3. appium 原理解析(转载雷子老师博客)

    appium 原理解析 原博客地址:https://www.cnblogs.com/leiziv5/p/6427609.html Appium是 c/s模式的appium是基于 webdriver 协 ...

  4. Tengine HTTPS原理解析、实践与调试【转】

    本文邀请阿里云CDN HTTPS技术专家金九,分享Tengine的一些HTTPS实践经验.内容主要有四个方面:HTTPS趋势.HTTPS基础.HTTPS实践.HTTPS调试. 一.HTTPS趋势 这一 ...

  5. Spring IOC设计原理解析:本文乃学习整理参考而来

    Spring IOC设计原理解析:本文乃学习整理参考而来 一. 什么是Ioc/DI? 二. Spring IOC体系结构 (1) BeanFactory (2) BeanDefinition 三. I ...

  6. Spring Security 解析(六) —— 基于JWT的单点登陆(SSO)开发及原理解析

    Spring Security 解析(六) -- 基于JWT的单点登陆(SSO)开发及原理解析   在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决定先把 ...

  7. gpfdist原理解析

    gpfdist原理解析 前言:gpfdist作为批量向postgresql写入数据的工具,了解其内部原理有助于正确使用以及提供更合适的数据同步方案.文章先简要介绍gpfdist的整体流程,然后针对重要 ...

  8. [原][Docker]特性与原理解析

    Docker特性与原理解析 文章假设你已经熟悉了Docker的基本命令和基本知识 首先看看Docker提供了哪些特性: 交互式Shell:Docker可以分配一个虚拟终端并关联到任何容器的标准输入上, ...

  9. 【算法】(查找你附近的人) GeoHash核心原理解析及代码实现

    本文地址 原文地址 分享提纲: 0. 引子 1. 感性认识GeoHash 2. GeoHash算法的步骤 3. GeoHash Base32编码长度与精度 4. GeoHash算法 5. 使用注意点( ...

随机推荐

  1. NOIP 2011 提高组 计算系数

    有二项式定理 `\left( a+b\right) ^{n}=\sum _{r=0}^{n}\left( \begin{matrix} n\\ r\end{matrix} \right) a^{n-r ...

  2. Logstash同步Oracle数据到ElasticSearch

    最近在项目上应用到了ElasticSearch和Logstash,在此主要记录了Logstash-input-jdbc同步Oracle数据库到ElasticSearch的主要步骤,本文是对环境进行简单 ...

  3. OUTLOOK连EXCHANGE,配置POP3时跳出错误问题

    "Authentication failed because outlook doesnt support any Resolved Question: "Authenticati ...

  4. 移动应用产品开发-android开发(一)

    最近公司希望增添移动开发业务,进行移动互联网开发的调研及产品需求调研. 我主要负责技术解决方案的研究,从android开发开始学习.同时跟经理一起与其他部门同事沟通了解移动开发方面的需求. 在了解an ...

  5. 【网络流24题】No.9 方格取数问题 (二分图点权最大独立集)

    [题意] 在一个有 m*n 个方格的棋盘中, 每个方格中有一个正整数. 现要从方格中取数, 使任意 2 个数所在方格没有公共边,且取出的数的总和最大.试设计一个满足要求的取数算法. 输入文件示例inp ...

  6. 虚拟机安装了ubuntu,忘记密码修复

    在虚拟机中按照以下步骤重新为用户设定新密码. 重启Ubuntu,随即长按shift进入grub菜单: 选择recovery mode,回车确认: 在Recovery Menu中,选择“Root Dro ...

  7. CSS3实现的player播放按钮

    完成的效果如下 查看效果并下载 Step 1:先了解border的原理: Step 2:HTML代码结构 <section class="playContainer"> ...

  8. 知乎上关于c和c++的一场讨论_看看高手们的想法

    为什么很多开源软件都用 C,而不是 C++ 写成? 余天升 开源社区一直都不怎么待见C++,自由软件基金会创始人Richard Stallman认为C++有语法歧义,这样子没有必要.非常琐碎还会和C不 ...

  9. Android常用Manager整理

    Android中常用Manager: ActivityManager,FragmentManager,PackagerManager, DownloadManager,ConnectivityMana ...

  10. ATL ActiveX 非管理员权限发布(支持vs2005)

    在win7系统中,vs2005开发的atl activex需要管理员权限才能注册. 解决方法: PerUserRegistration.h #pragma once class PerUserRegi ...