session原理解析
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>" + " <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原理解析的更多相关文章
- Spring Session原理解析
前景提要: @EnableRedisHttpSession导入RedisHttpSessionConfiguration.classⅠ.被RedisHttpSessionConfiguration继承 ...
- 从session原理出发解决微信小程序的登陆问题
声明:本文为作者原创文章,转载请注明出处 https://www.cnblogs.com/MaMaNongNong/p/9127416.html 原理知识准备 对于已经熟悉了session原理的同 ...
- appium 原理解析(转载雷子老师博客)
appium 原理解析 原博客地址:https://www.cnblogs.com/leiziv5/p/6427609.html Appium是 c/s模式的appium是基于 webdriver 协 ...
- Tengine HTTPS原理解析、实践与调试【转】
本文邀请阿里云CDN HTTPS技术专家金九,分享Tengine的一些HTTPS实践经验.内容主要有四个方面:HTTPS趋势.HTTPS基础.HTTPS实践.HTTPS调试. 一.HTTPS趋势 这一 ...
- Spring IOC设计原理解析:本文乃学习整理参考而来
Spring IOC设计原理解析:本文乃学习整理参考而来 一. 什么是Ioc/DI? 二. Spring IOC体系结构 (1) BeanFactory (2) BeanDefinition 三. I ...
- Spring Security 解析(六) —— 基于JWT的单点登陆(SSO)开发及原理解析
Spring Security 解析(六) -- 基于JWT的单点登陆(SSO)开发及原理解析 在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决定先把 ...
- gpfdist原理解析
gpfdist原理解析 前言:gpfdist作为批量向postgresql写入数据的工具,了解其内部原理有助于正确使用以及提供更合适的数据同步方案.文章先简要介绍gpfdist的整体流程,然后针对重要 ...
- [原][Docker]特性与原理解析
Docker特性与原理解析 文章假设你已经熟悉了Docker的基本命令和基本知识 首先看看Docker提供了哪些特性: 交互式Shell:Docker可以分配一个虚拟终端并关联到任何容器的标准输入上, ...
- 【算法】(查找你附近的人) GeoHash核心原理解析及代码实现
本文地址 原文地址 分享提纲: 0. 引子 1. 感性认识GeoHash 2. GeoHash算法的步骤 3. GeoHash Base32编码长度与精度 4. GeoHash算法 5. 使用注意点( ...
随机推荐
- python面向对象编程实例解析
1. 类和函数 面向对象编程的例子: #!/usr/bin/env python # -*- coding: utf-8 -*- class Person(object): #在属性和变量的前面增加“ ...
- USB otg 学习笔记
1 USB OTG的工作原理 OTG补充规范对USB2.0的最重要的扩展是其更具节能性的电源管理和允许设备以主机和外设两种形式工作.OTG有两种设备类型:两用OTG设备(Dualrole device ...
- 如何设置SVN提交时强制添加注释
windows版本: 1.新建一个名为pre-commit.bat的文件并将该文件放在创建的库文件的hooks文件夹中 2.pre-commit.bat文件的内容如下: @echo off set S ...
- Entity Framework系列文章导航
转自:http://www.cnblogs.com/xray2005/archive/2011/10/11/2206746.html Entity Framework4.0系列文章 需要说明的是,以下 ...
- (转载)PHP 判断常量,变量和函数是否存在
(转载)http://www.jb51.net/article/17881.htm 如果你看懂了上面一句话,那么接下来都是废话,PHP手册写的还是很全的.一句话就把我标题中的问题全部解决了. 还是举几 ...
- Count the string -- HDOJ 3336
Count the string Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- linux 下的sublime
Sublime Text 2 的安装 : 在官方网站下载Linux版本 Or 执行 # wget http://c758482.r82.cf2.rackcdn.com/Sublime%20Tex ...
- Selenium - WebDriver 小结(1)
public class Base { SimpleDateFormat formatterTime = new SimpleDateFormat("yyyyMMdd_hhmmssa&quo ...
- JavaScript---网络编程(8)-DHTML技术演示(1)
DHTML技术使用的基本思路: 1. 用标签封装数据-html范畴 2. 定义样式-css范畴 3. 明确事件源.事件和要处理的节点-dom范畴 4. 明确具体的操作方式,其实就是事件的处理内容(过程 ...
- ORM介紹及ORM優點、缺點
主要內容: 1.ORM的概念 2.為什麽要使用ORM 3.ORM的優缺點 4..Net中有那些ORM產品 5.總結 一.ORM的概念 ORM,即Object-Relational Mapping( ...