zoukankan      html  css  js  c++  java
  • web中的cookie管理

      本篇是以JSP为背景介绍,但是在web开发中也是相同的原理。

      什么是cookie

      由于http是一种无状态的协议,因此服务器收到请求后,只会当做一次新的请求。即便你重复发送了1000次同样的请求,这1000次都属于独立的请求。

      这样显然效率很低,如果要登录某个网站,后期的操作都与用户身份有关,难道还得没操作一个页面都得登录一次?

      于是cookie和session就诞生了。

      cookie和session都是用于帮助http进行状态管理的一种手段。

      cookie与session的区别

      cookie与session的区别可以通过下面几点区分:

      1 保存位置:cookie保存在客户端浏览器中;session保存在服务器端。

      2 生命周期:cookie由用户指定或者使用默认的过期时间,在这段期限内cookie都保存在客户端本地;session属于一次会话,如果会话关闭,浏览器关闭,服务器启动都会导致session的清除。

      3 数据类型:cookie其实就是一堆字符串;session是某种Object对象。

      4 安全性:cookie一般只保存一些用户的行为习惯等等,像用户名密码肯定都需要经过加密的,即使泄露了也无关紧要;session则保存用户相关的重要内容。

      cookie的使用过程

      如果要保存cookie

      首先需要创建一个Cookie对象,然后通过把它添加到response对象中,返回给客户端即可。

      Cookie对象中的数据就自动保存在客户端了。

      如果要使用cookie

      可以通过request对象直接查询cookie信息,并且比对是否含有自己使用的数据。

      Cookie中常用的方法

      1 创建Cookie对象

    Cookie usernameCookie = new Cookie("username",username);

      2 设置过期时间,以秒为单位

    usernameCookie.setMaxAge(864000);

      3 保存cookie

    response.addCookie(usernameCookie);

      4 获取cookie数据

    Cookie[] cookies = request.getCookies();

      5 提取关键数据

    Cookie[] cookies = request.getCookies();
    if(cookies!=null && cookies.length>0){
        for(Cookie c:cookies){
            if(c.getName().equals("username")){
                response.addCookie(c);
            }
        }
    }

      JSP中cookie使用样例

      业务场景:

      1 login.jsp登录用户名密码,可以设置是否记录cookie;如果之前登陆过,则自动填写cookie中的信息。

      2 跳转到doLogin.jsp界面,进行cookie的保存于清除。如果前一页设置保存,则保存cookie信息;如果前一页设置不保存,则清除信息。

      3 通过URL跳转到users.jsp页面,可以提取cookie中的相关信息。

      login.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8"
        import="java.net.*"
        pageEncoding="utf-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>用户登录</title>
    </head>
    <body>
        <h1>用户登录</h1>
        <hr>
            <%
            request.setCharacterEncoding("utf-8");
            String username = "";
            String password = "";
            
            Cookie[] cookies = request.getCookies();
            if(cookies!=null && cookies.length>0){
                for(Cookie c:cookies){
                    if(c.getName().equals("username")){
                        username = URLDecoder.decode(c.getValue(),"utf-8");
                    }
                    if(c.getName().equals("password")){
                        password = URLDecoder.decode(c.getValue(),"utf-8");
                    }
                }
            }
        %>
        <form name="loginForm" action="doLogin.jsp" method="post">
            <table>
                <tr>
                    <td>username</td>
                    <td><input type="text" name="username" value=<%=username%>></input></td>
                </tr>
                <tr>
                    <td>password</td>
                    <td><input type="password" name="password" value=<%=password%>></input></td>
                </tr>
                <tr>
                    <td>
                        <input type="checkbox" name="isUseCookie" checked="true"/>记住登录状态
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center"><input type="submit" value="submit"/></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
    View Code

      doLogin.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8"
        import="java.net.*"
        pageEncoding="utf-8"%>
        
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>用户登录</title>
    </head>
    <body>
        <h1>javaBeans</h1>
        <hr>
        <%
            //保证request以及response的编码 
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
        
            String[] isUseCookies = request.getParameterValues("isUseCookie");
            if(isUseCookies!=null && isUseCookies.length>0 ){
                //使用URLEncoder解决cookie中中文问题
                String username = URLEncoder.encode(request.getParameter("username"),"utf-8");
                String password = URLEncoder.encode(request.getParameter("password"),"utf-8");
                
                Cookie usernameCookie = new Cookie("username",username);
                Cookie passwordCookie = new Cookie("password",password);
                usernameCookie.setMaxAge(864000);
                passwordCookie.setMaxAge(864000);
                
                response.addCookie(usernameCookie);
                response.addCookie(passwordCookie);
            }else{
                Cookie[] cookies = request.getCookies();
                if(cookies!=null && cookies.length>0){
                    for(Cookie c:cookies){
                        if(c.getName().equals("username")||c.getName().equals("password")){
                            c.setMaxAge(0);
                            response.addCookie(c);
                        }
                    }
                }
            }
        %>
        <a href="users.jsp" target="_blank">check user info</a>
    </body>
    </html>
    View Code

      users.jsp

    <%@ page language="java" import="java.util.*,java.io.*,java.net.*" contentType="text/html; charset=utf-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <h1>cookie</h1>
        <%
            request.setCharacterEncoding("utf-8");
        
            String username = "";
            String password = "";
    
            Cookie[] cookies = request.getCookies();
            if(cookies!=null && cookies.length>0){
                for(Cookie c:cookies){
                    if(c.getName().equals("username")){
                        username = URLDecoder.decode(c.getValue(),"utf-8");
                    }
                    if(c.getName().equals("password")){
                        password = URLDecoder.decode(c.getValue(),"utf-8");
                    }
                }
            }
        %>
        用戶名:<%=username %>
        密碼:<%=password %>
    </body>
    </html>
    View Code

      其中关于编码问题,可以参考:中文乱码问题

  • 相关阅读:
    PHP 二维数组排序
    linux CentOS7.* 上安装 ffmpeg 扩展
    ajax删除,
    ajax的格式、简单使用编写,
    多对多作为外键,getset方法实现
    外键介绍,manytomany介绍,filter跨表双下划线
    student学生信息表增删改
    数据库表的增删改查学生信息管理
    session保存信息用数据库
    cookie实现访问index无法访问必须从login走,返回固定的session值,
  • 原文地址:https://www.cnblogs.com/xing901022/p/4359732.html
Copyright © 2011-2022 走看看