JavaWeb(二)cookie与session的应用
前言
前面讲了一堆虚的东西,所以这篇我们来介绍一下cookie和session的应用。
一、使用cookie记住用户名
1.1、思路介绍
1.2、实现代码
1)LoginServlet
package com.zyh.cookie; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String userName = "";
String checked = ""; //得到客户端保存的cookie数据
Cookie[] cookies = request.getCookies();
//因为第一次的时候没有cookie,所以不谢cookies!=null的话,空指针异常的。
for (int i = ; cookies!=null&&i < cookies.length; i++) {
if("userName".equals(cookies[i].getName())){
userName = cookies[i].getValue();
checked = "checked='checked'";
}
} out.print("<form action='"+request.getContextPath()+"/doLoginServlet' type='post'>");
out.print("用户名:<input type='text' name='userName' value='"+userName+"' /><br/>");
out.print("密码:<input type='password' name='pwd' /><br/>");
out.print("记住用户名:<input type='checkbox' name='remember' "+checked+" /><br/>");
out.print("<input type='submit' value='提交' /><br/>");
out.print("</form>"); } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { } }
LoginServlet
2)DoLoginServlet
package com.zyh.cookie; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class DoLoginServlet extends HttpServlet { 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 userName = request.getParameter("userName");
String pwd = request.getParameter("pwd");
String remember = request.getParameter("remember"); Cookie cookie = new Cookie("userName", userName);
//处理业务逻辑
if("faker".equals(userName)&&"".equals(pwd)){
if(remember!=null){//注意:如果text、password不填为空,而checkbox不填则为null值
cookie.setPath("/");
cookie.setMaxAge(Integer.MAX_VALUE); //设置cookie有效保存时间
}else{
cookie.setMaxAge(); //删除cookie
}
response.addCookie(cookie); //将cookie写会客户端
out.print("登录成功");
}else{
out.print("登录失败");
//设置2秒钟重新登录
response.setHeader("refresh", "2;url="+request.getContextPath()+"/loginServlet");
}
//分发转向 }
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { } }
DoLoginServlet
1.3、测试
1)访问:http://localhost:8080/Web_cookieandsession/loginServlet
输入faker、123,并且记住用户名
2)结果
3)因为我的cookie的有效时间设置的是永久,假如我们是过了几天再次去访问
二、使用cookie显示上次浏览商品
2.1、思路分析
实现过程
2.2、实现代码
1)创建一个Book实体类
package com.zyh.domain; public class Book {
private String id;
private String name;
private String price;
private String author; public Book(String id, String name, String price, String author) {
super();
this.id = id;
this.name = name;
this.price = price;
this.author = author;
} 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 getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price
+ ", author=" + author + "]";
} }
Book
2)创建一个工具类用于保存所有图书:DBUtil
package com.zyh.util; import java.util.HashMap;
import java.util.Map; import com.zyh.domain.Book; public class DBUtil {
private static Map<String,Book> books = new HashMap<String, Book>(); static{
books.put("1,",new Book("","揭秘Spring","","张总工"));
books.put("2,",new Book("","HTTP权威指南","","刘成龙"));
books.put("3,",new Book("","java核心基础","","马成功"));
books.put("4,",new Book("","linux私房菜","","鸟叔"));
books.put("5,",new Book("","javaweb入门","","杰克"));
} //得到所有书
public static Map<String,Book> getBooks(){
return books;
} /**
* 根据id查找指定的书
* @param id
* @return
*/
public static Book findBookById(String id){
return books.get(id);
} }
DBUtil
3)ShowAllBooksServlet
package com.zyh.history; import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map; 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 com.zyh.domain.Book;
import com.zyh.util.DBUtil; public class ShowAllBooksServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("本网站的书有:<br />");
Map<String, Book> books = DBUtil.getBooks();
for (Map.Entry<String, Book> book : books.entrySet()) {
out.write("<a href='"+request.getContextPath()+"/showBookDetail?id="+book.getKey()+"' target='_blank'>"+book.getValue().getName()+"</a><br />");
} out.println("<hr/>您最近浏览过的书有:<br />");
Cookie[] cookies = request.getCookies();
for(int i=;cookies!=null&&i<cookies.length;i++){
if("historyBookId".equals(cookies[i].getName())){
String value = cookies[i].getValue(); //2-1-3
String[] ids = value.split("-");
for(int j = ;j<ids.length;j++){
Book book = DBUtil.findBookById(ids[j]); //根据id得到指定的书
out.print(book.getName()+"<br />");
}
}
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { } }
ShowAllBooksServlet
4)ShowBookDetail
package com.zyh.history; import java.io.IOException;
import java.io.PrintWriter;
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 com.zyh.domain.Book;
import com.zyh.util.DBUtil; public class ShowBookDetail extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//显示图书详细信息 //获取id
String id = request.getParameter("id");
Book book = DBUtil.findBookById(id); //out.write(book.toString());
out.print(book); //把当前浏览过的书的id写回到客户端
String historyBookId = organizedId(id,request);
Cookie ck = new Cookie("historyBookId",historyBookId);
ck.setPath("/");
ck.setMaxAge(Integer.MAX_VALUE); response.addCookie(ck); } private String organizedId(String id, HttpServletRequest request) {
//获取客户端的cookie
Cookie[] cookies = request.getCookies(); if(cookies==null){
return id;
} //查找有没有一个name叫historyBookId的cookie
Cookie historyBook = null;
for (int i = ; i < cookies.length; i++) {
if("historyBookId".equals(cookies[i].getName())){
historyBook = cookies[i];
}
} //如果没有一个historyBookId的cookie,则返回id
if(historyBook==null){
return id;
} String value = historyBook.getValue(); //1-2-3
String[] values = value.split("-");
LinkedList<String> list = new LinkedList<String>(Arrays.asList(values)); if(list.size()<){//1 2
if(list.contains(id)){
list.remove(id); //如果包含当前id的值,则删除这个id
}
}else{//说明有三本书的id了
list.removeLast(); //把最后一个id删除
}
list.addFirst(id); //最新的书添加到最前面 StringBuffer sb = new StringBuffer();
for(int i=;i<list.size();i++){
if(i>){
sb.append("-");
}
sb.append(list.get(i));
}
// System.out.println(sb); //1-2-3
return sb.toString();
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { } }
ShowBookDetail
2.3、测试
1)访问:http://localhost:8080/Web_cookieandsession/showAllBooksServlet
2)点击java核心基础
查看书的详细信息:
刷新第一个网页:
这里最多就能显示最近浏览过的3本书
三、session实现简单的购物车功能
3.1、思路分析
3.2、实现代码
1)需要前面写的Book的实体类,和存储书的工具类DBUtil
2)ShowAllBooksSession
package com.zyh.sessioncart; 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 com.zyh.domain.Book;
import com.zyh.util.DBUtil; public class ShowAllBooksSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); out.print("本网站有以下好书:<br />");
Map<String, Book> books = DBUtil.getBooks();
for(Map.Entry<String, Book> book :books.entrySet()){
out.print("<a href='"+request.getContextPath()+"/addCart?id="+book.getKey()+"'>"+book.getValue().getName()+"</a><br />");
} out.print("<a href='"+request.getContextPath()+"/showCart'>查看购物车</a>");
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
} }
ShowAllBooksSession
3)AddCart
package com.zyh.sessioncart; 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 com.zyh.domain.Book;
import com.zyh.util.DBUtil; public class AddCart extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); //根据id得到书
String id = request.getParameter("id");
Book book = DBUtil.findBookById(id); //得到session对象
HttpSession session = request.getSession(); //从session当中取出list(购物车)
List<Book> list = (List<Book>) session.getAttribute("cart");
if(list==null){
list = new ArrayList<Book>();
}
list.add(book);
session.setAttribute("cart", list); //把list放回到session域当中 out.print("购买成功!2秒钟跳回");
response.setHeader("refresh", "2;url="+request.getContextPath()+"/showAllBooksSession"); }
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
} }
AddCart
4)ShowCart
package com.zyh.sessioncart; 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 com.zyh.domain.Book; public class ShowCart extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("购物车有以下商品:<br />");
//得到session对象
HttpSession session = request.getSession();
List<Book> books = (List<Book>) session.getAttribute("cart");
if(books==null){
out.print("你什么都没有买");
//这样设置的话,上面还没有看到就直接跳转了
// response.sendRedirect(request.getContextPath()+"/showAllBooksSession");
response.setHeader("refresh", "2;url="+request.getContextPath()+"/showAllBooksSession");
return; //如果没有买执行下面的会出现空指针
}
for(Book book:books){
out.write(book.getName()+"<br />");
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
} }
ShowCart
3.3、测试
1)访问:http://localhost:8080/Web_cookieandsession/showAllBooksSession
2)点击java核心基础,2秒自动跳转回去
3)查看购物车
JavaWeb(二)cookie与session的应用的更多相关文章
- JavaWeb之Cookie和Session的区别
Cookie和Session的区别 一.cookie机制和session机制的区别 ********************************************************** ...
- java基础学习:JavaWeb之Cookie和Session
一.会话概述 1.1.什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话其中不管浏览器发送多少请求,都视为一次会话,直到 ...
- JavaWeb 补充(Cookie&JSP&Session)
1. 会话技术 1. Cookie 2. Session 2. JSP:入门学习 会话技术 1. 会话:一次会话中包含多次请求和响应. * 一次会话:浏览器第一次给服务器资源发 ...
- 【JavaWeb】 Cookie和Session
Session和Cookie出现的原因: 由于Http是无状态的协议,会话之间没有任何关联,也就是上一次会话和下一次会话没有任何关联,因此出现了会话技术Cookie和Session 下面分别从Cook ...
- 【Javaweb】Cookie和Session
会话技术 什么是会话 从浏览器访问服务器开始,到访问服务器结束,浏览器关闭为止的这段时间内容产生的多次请求和响应,合起来叫做浏览器和服务器之间的一次会话 会话管理作用 共享数据用的,并且是在不同请求间 ...
- IT兄弟连 JavaWeb教程 Cookie和Session应用结合使用
一般对于不要求安全的非敏感数据,建议存储在Cookie中! 对于敏感的数据,占用空间较小的,建议存储在Session中! 对于敏感的,较大的数据,存数据库!
- Flask (二) cookie 与 session 模型
会话技术 Cookie 客户端端的会话技术 cookie本身由浏览器保存,通过Response将cookie写到浏览器上,下一次访问,浏览器会根据不同的规则携带cookie过来 特点: - 客 ...
- Django:Admin,Cookie,Session
一. Admin的配置 1.Admin基础设置 admin是django强大功能之一,它能够从数据库中读取数据,呈现在页面中,进行管理.默认情况下,它的功能已经非常强大,如果你不需要复杂的功能,它已经 ...
- JavaWeb(二)会话管理之细说cookie与session
前言 前面花了几篇博客介绍了Servlet,讲的非常的详细.这一篇给大家介绍一下cookie和session. 一.会话概述 1.1.什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接, ...
随机推荐
- 【bird-front】前端框架介绍
bird前端项目,基于react.antd.antd-admin,封装常用数据组件,细粒度权限解决方案. bird-front是基于react的后台管理系统前端项目,框架构建部分严重借鉴于antd管理 ...
- iOS学习之Socket使用简明教程- AsyncSocket
转载自:http://my.oschina.net/joanfen/blog/287238 如果需要在项目中像QQ微信一样做到即时通讯,必须使用socket通讯,本人也是刚学习,分享一下,有什么不对的 ...
- JDK 1.8 源码阅读和理解
根据 一篇文章教会你,如何做到招聘要求中的“要有扎实的Java基础” 的指引,决定开始阅读下JDK源码. 本文将作为源码阅读总纲 一.精读部分 java.io java.lang java.util ...
- Servlet小总结
Servlet Servlet(服务器端小程序)是使用Java语言编写的服务器端程序,像JSP一样,生成动态的Web页.Servlet主要运行在服务器端,并由服务器调用执行. Servlet处理的基本 ...
- java 学习笔记之 流、文件的操作
ava 学习笔记之 流.文件的操作 对于一些基础的知识,这里不再过多的解释, 简单的文件查询过滤操作 package com.wfu.ch08; import java.io.File; import ...
- 我是如何确认线上CLOSE_WAIT产生的原因及如何解决的。
1.阐述 内部架构:Tomcat应用程序---> nginx ---> 其他Tomcat应用程序,内部Tomcat应用通过nginx调用其他应用. HTTP插件:HttpClient 4. ...
- python 中一些关键字的区别
一.raw_input 和input input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的 1.当输入为纯数字时 input返回的是数值类型, ...
- mac安全权限解决
如果有以下提示的,并不是文件损坏了,而是macOS Sierra新系统取消了安装本地程序的功能. 解决办法如下: 1.首先打开终端(找不到哪里打开终端 command+空格 搜索 "终端 ...
- JavaScript的DOM编程--05--获取文本节点
获取文本节点: 1). 步骤: 元素节点 --> 获取元素节点的子节点 2). 若元素节点只有文本节点一个子节点, 例如 <li id="bj" name=" ...
- 微信小程序开发之图片预览
实现图片的展示和大图预览 使用wx.previewImage(OBJECT)来实现 OBJECT参数说明: 参数 类型 必填 说明 current String 否 当前显示图片的链接,不填则默认为 ...