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.什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接, ...
随机推荐
- Data Base mongodb driver2.5环境注意事项
mongodb driver2.5环境注意事项 一.问题: 如果使用vs2012开发就会报这个错误: 未能加载文件或程序集“System.Runtime.InteropServices.Runtime ...
- iOS 环信集成项目应用
环信iOS端3.0版本集成记录--聊天界面篇 环信离线推送证书... 1,环信处在后台的时候,消息的接收与推送 离线发推送 配置属性 EMCallOptions *options = [[EMClie ...
- 监听键盘弹起View上调
可以用三方库IQKeyboardManager 用这个第三方 http://www.jianshu.com/p/f8157895 #pragma mark - keyboard events - // ...
- open-falcon(v0.2)安装grafana部署
下载rpm wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana-4.4.3-1.x86_64.rpm 本地 ...
- CSS3 自定义动画(animation)
除了在之前的文章中介绍过的 CSS3 的变形 (transformation) 和转换 (transition) 外,CSS3 还有一种自由度更大的自定义动画,开发者甚至可以使用变形(transfor ...
- php SeasLog使用以及liunx环境下安装
1.下载SeasLog http://pecl.php.net/package/SeasLog php官方 https://github.com/Neeke/SeasLog 作者的github 2. ...
- collections --Counter
collections 模块--Counter 目的是用来跟踪值出现的次数.是一个无序的容器类型,以字典的键值对形式存储,其中元素为 key,其计数作为 value.计数值可以是任意的 Integer ...
- Linux入门篇(一)——基本命令
这一系列的Linux入门都是本人在<鸟哥的Linux私房菜>的基础上总结的基本内容,主要是记录下自己的学习过程,也方便大家简要的了解 Linux Distribution是Ubuntu而不 ...
- Vue自己写组件——Demo详细步骤
公司近期发力,同时开了四五个大项目,并且都是用Vue来做的,我很荣幸的被分到了写项目公用模块的组,所以需要将公用的部分提取成组件的形式,供几个项目共同使用,下面详细讲一下写Vue组件的具体步骤. 一. ...
- windows系统下使用cd命令
如果要切换到D:\Program Files目录下,大多数人会想当然的在命令行窗口输入 cd D:\Program Files回车. 如下所示: 发现并没有切换到D:\Program Files. 正 ...