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. Linq学习之旅——LINQ查询表达式

    1. 概述 2. from子句 3. where子句 4. select子句 5. group子句 6. into子句 7. 排序子句 8. let子句 9. join子句 10. 小结 1. 概述 ...

  2. .h头文件、 .lib库文件、 .dll动态链接库文件之间的关系

    转自.h头文件. .lib库文件. .dll动态链接库文件之间的关系 h头文件作用:声明函数接口 dll动态链接库作用:含有函数的可执行代码 lib库有两种: (1)静态链接库(Static Liba ...

  3. [ecmall]Ecmall 后台添加模板编辑区

    例如,想把品牌/index.php?app=brand页面做成可编辑的. 首先,找到后台admin\includes\menu.inc.php第61行 'template' => array( ...

  4. Delphi xe10下载(包含破解补丁和破解视频)

    软件名称:RAD Studio 10 Seattle软件大小:7.18 GB RAD Studio 10 Seattle官方下载地址:http://altd.embarcadero.com/downl ...

  5. King(差分约束)

    http://poj.org/problem?id=1364 题意真心看不大懂啊... 现在假设有一个这样的序列,S={a1,a2,a3,a4...ai...at}其中ai=a*si,其实这句可以忽略 ...

  6. SharePoint2010沙盒解决方案基础开发——关于TreeView树形控件读取列表数据(树形导航)的webpart开发及问题

    转:http://blog.csdn.net/miragesky2049/article/details/7204882 SharePoint2010沙盒解决方案基础开发--关于TreeView树形控 ...

  7. HDU-1540          Tunnel Warfare

    Tunnel Warfare Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)To ...

  8. 基于WCF大型分布式系统的架构设计

    在大型系统中应用中,一个架构设计较好的应用系统,其总体功能肯定是由很多个功能模块所组成的,而每一个功能模块所需要的数据对应到数据库中就是一个或多个表.而在架构设计中,各个功能模块相互之间的交互点 越统 ...

  9. c# 如何通过反射 获取\设置属性值

    c# 如何通过反射 获取\设置属性值 //定义类public class MyClass{public int Property1 { get; set; }}static void Main(){M ...

  10. PCB覆铜时的安全距离

    覆铜的安全间距(clearance)一般是布线的安全间距的二倍.但是在没有覆铜之前,为布线而设置好了布线的安全间距,那么在随后的覆铜过程中,覆铜的安全间距也会默认是布线的安全距离.这样与预期的结果不一 ...