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 = 0; 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 { } }
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)&&"123".equals(pwd)){ if(remember!=null){//注意:如果text、password不填为空,而checkbox不填则为null值 cookie.setPath("/"); cookie.setMaxAge(Integer.MAX_VALUE); //设置cookie有效保存时间 }else{ cookie.setMaxAge(0); //删除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 { } }
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 + "]"; } }
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("1","揭秘Spring","30","张总工")); books.put("2,",new Book("2","HTTP权威指南","70","刘成龙")); books.put("3,",new Book("3","java核心基础","20","马成功")); books.put("4,",new Book("4","linux私房菜","66","鸟叔")); books.put("5,",new Book("5","javaweb入门","30","杰克")); } //得到所有书 public static Map<String,Book> getBooks(){ return books; } /** * 根据id查找指定的书 * @param id * @return */ public static Book findBookById(String id){ return books.get(id); } }
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=0;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 = 0;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 { } }
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 = 0; 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()<3){//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=0;i<list.size();i++){ if(i>0){ 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 { } }
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 { } }
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 { } }
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 { } }
3.3、测试
1)访问:http://localhost:8080/Web_cookieandsession/showAllBooksSession
2)点击java核心基础,2秒自动跳转回去
3)查看购物车