专栏首页LanceToBigDataJavaWeb(二)cookie与session的应用

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)查看购物车

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • struts2(一)之初识struts2

    前言   我们都知道struts2是一个框架,那什么是框架呢?很多人其实不太明白,其实框架就是一个半成品,别人将一些功能已经写好了,我们只需要拿来用即可,像我们...

    用户1195962
  • Hadoop(十一)Hadoop IO之序列化与比较功能实现详解

    前言   上一篇给大家介绍了Hadoop是怎么样保证数据的完整性的,并且使用Java程序来验证了会产生.crc的校验文件。这一篇给大家分享的是Hadoop的序列...

    用户1195962
  • JavaWeb(五)之JSTL标签库

    前言   前面介绍了EL表达式,其实EL表达式基本上是和JSTL核心标签库搭配一起使用才能发挥效果的。接下来让我们一起来认识一下吧!   在之前我们学过在JSP...

    用户1195962
  • Mybatis案例升级版——小案例大道理

    这几天看了一本书《原则》,在上面看到了一句话叫“每个人都把自己眼界的局限当成世界的局限”,大学生是?,大学就是鱼缸,世界很大,希望大家好好努力,不要让“贫穷”限...

    泰斗贤若如
  • Java工具集-阿里云短信API工具

    cwl_java
  • 浅谈面试中的OO设计问题

    OO设计问题是电面或者onsite中常考的问题,尤其对以Java为主要开发语言的公司(比如Amazon),OO设计问题可以算必考。OO设计题目的特点是题目非常...

    包子面试培训
  • Spring全家桶之SpringBoot——初级阶段

    • Spring Boot 设计目的是用来简化新Spring 应用的初始搭建以及开发过程。 • 嵌入的Tomcat,无需部署WAR 文件 • Spring ...

    时间静止不是简史
  • Android OkGo网络请求库 自定义回调支持带泛型的对象

    这里写了两种方式请求接口 (文中用了Java和Kotlin两种语言 没有特殊标示的都是Java)

    剑行者
  • springboot+security 数据库中读取账号密码 使用security加密规则 实体类继承security的实体接口

    码云地址:https://gitee.com/huatao1994/springSecurity

    用户5899361
  • spring的简易实现(一)

    在第一部分我们实现读取xml的配置,然后实例化xml中的bean 首先定义一个xml和相关的class类

    Theone67

扫码关注云+社区

领取腾讯云代金券