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. C#之装箱与拆箱

    C#中值类型和和引用类型实质上是同源的,所以不但可以从值类型和引用类型之间进行转换,也可以在值类型和引用类型之间进行转换.,但是两者使用的内存类型不同,使他们的转换变得复杂. 1.装箱: 在C#中通常 ...

  2. flume 报File Channel transaction capacity cannot be greater than the capacity of the channel capacity错误

    今天在部署flume集群时,在启动collector服务器没报错,启动agent服务器报错: File Channel transaction capacity cannot be greater t ...

  3. ANDROID_MARS学习笔记_S05_002_给传感器注册listener

    1 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); se ...

  4. qt 原子操作 QAtomicInt(++和--都不是原子操作:都包含三条机器指令)

    ++和--都不是原子操作:都包含三条机器指令 http://sroply.blog.163.com/blog/static/17092651920106117251539/

  5. Android开源项目发现---Menu 篇(持续更新)

    1. MenuDrawer 滑出式菜单,通过拖动屏幕边缘滑出菜单,支持屏幕上下左右划出,支持当前View处于上下层,支持Windows边缘.ListView边缘.ViewPager变化划出菜单等. 项 ...

  6. 在ubuntu12.04下编译android4.1.2添加JNI层出现问题

    tiny4412学习者,在ubuntu12.04下编译android4.1.2添加JNI层出现问题: (虚心请教解决方法) trouble writing output: Too many metho ...

  7. 无法使用以下搜索标准找到 X.509 证书: StoreName“My”、StoreLocation“LocalMachine”、FindType“FindBySubjectName”、FindValue“MyWebSite”。

    http://www.codeproject.com/Articles/96028/WCF-Service-with-custom-username-password-authenti 需要制作证书 ...

  8. oracle查询转换_inlist转换

    oracle的optimizer会对一些sql语句进行查询转换,比如: 合并视图 子查询非嵌套化 inlist转换 下面讲讲遇到的in list转化优化的案例: create table test( ...

  9. JSOI2008 火星人prefix

    1014: [JSOI2008]火星人prefix Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 2918  Solved: 866[Submit][ ...

  10. c++ lambda返回类型自动推导的一些需要注意的地方

    一句话,lambda返回类型自动推导走的是auto,而不是decltype,注意. class ObjectA { public: ObjectA() { val_ = ++g; } ObjectA( ...