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.什么是会话? 会话可简单理解为:用户开一个浏览器,点击多个超链接, ...
随机推荐
- 《高性能MySQL(第3版)》【PDF】下载
内容简介 <高性能mysql(第3版)>是mysql 领域的经典之作,拥有广泛的影响力.第3版更新了大量的内容,不但涵盖了最新mysql5.5版本的新特性,也讲述了关于固态盘.高可扩展性设 ...
- 同时只允许Count个线程访问同一块区域的实现方式
转载请注明出处. 好吧,后来才发现有Semaphore和SemaphoreSlim这两个类. 以前的答案: 最近.Net项目中用到了网页截图功能,这个截图功能是类似后台开了一个IE浏览器默默加载某个网 ...
- MySQL锁总结
本文同时发表在https://github.com/zhangyachen/zhangyachen.github.io/issues/78 MySQL 锁基础 参考了何登成老师文章的结构MySQL 加 ...
- 5.Nginx作为web缓存服务器
Nginx作为web缓存服务器 从0.7.48版本开始,Nginx支持类似Squid的缓存功能.Nginx的web缓存服务主要由proxy_cache相关命令集合fastcgi_cache相关命令集构 ...
- 设计模式之 - 模板模式(Template Pattern)
引入:这几天在看一本讲spring源码的书<SPRING技术内幕>里面在讲加载配置文件的时候,可以有不同的加载方式,如根据文件系统目录加载配置文件(FileSystemXmlApplica ...
- input同步标签内容——函数
html部分: <h3 class="font18" id="tit1">微蜂传媒电子商务有限公司</h3> <span clas ...
- Webpack 2 视频教程 009 - 配置 ESLint 实现代码规范自动测试 (上)
原文发表于我的技术博客 这是我免费发布的高质量超清「Webpack 2 视频教程」. Webpack 作为目前前端开发必备的框架,Webpack 发布了 2.0 版本,此视频就是基于 2.0 的版本讲 ...
- 一起学Linux02之Linux系统启动过程
这个Linux系统启动过程啊,说实话,我认为,刚学习的时候看几遍,了解一下就好.现在的主要任务是用.熟练了之后再来深究这个不急. 下面我就简单地说说吧. Linux系统的启动主要分为下列步骤: 1 内 ...
- iOS学习——UI相关小结
1 StoryBoard: 在Info.plist中可以查看Main storyboard,即入口storyboard,默认为main.storyboard,可以修改为自己创建的storybo ...
- Nginx集群之SSL证书的WebApi微服务
目录 1 大概思路... 1 2 Nginx集群之SSL证书的WebApi微服务... 1 3 HTTP与HTTPS(SSL协议)... 1 4 Ope ...