欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

cookie与session

程序员文章站 2022-10-06 21:58:05
COOKIE与SESSION 1,基本概念 cookie机制采用的是在客户端保持状态的方案,当你在浏览网站的时候,cookie是一个文本信息,会帮你在网站上所打的文字或是一些选择,都纪录下来。当下次你再浏览同一个网站,首先会查一下有没有上次留下的资料,有的话,就会依据 Cookie里的内容来判断使用 ......

COOKIESESSION

1,基本概念

cookie机制采用的是在客户端保持状态的方案,当你在浏览网站的时候,cookie是一个文本信息,会帮你在网站上所打的文字或是一些选择,都纪录下来。当下次你再浏览同一个网站,首先会查一下有没有上次留下的资料,有的话,就会依据 Cookie里的内容来判断使用者,送出特定的网页内容给你。

cookie机制。正统的cookie分发是通过扩展HTTP协议来实现的,服务器通过在HTTP的响应头中加上一行特殊的指示以提示浏览器按照指示生成相应的cookie。然而纯粹的客户端脚本JavaScript或者VBScript也可以生成cookie。而cookie的使用是由浏览器按照一定的原则在后台自动发送给服务器的。浏览器检查所有存储的cookie,如果某个cookie所声明的作用范围大于等于将要请求的资源所在的位置,则把该cookie附在请求资源的HTTP请求头上发送给服务器。

cookie的内容主要包括:名字,值,过期时间,路径和域。路径与域一起构成cookie的作用范围。若不设置过期时间,则表示这

cookie的生命期为浏览器会话期间,关闭浏览器窗口,cookie就消失。这种生命期为浏览器会话期的cookie被称为会话cookie。

会话cookie一般不存储在硬盘上而是保存在内存里,当然这种行为并不是规范规定的。若设置了过期时间,浏览器就会把cookie

保存到硬盘上,关闭后再次打开浏览器,这些cookie仍然有效直到超过设定的过期时间。存储在硬盘上的cookie可以在不同的浏

览器进程间共享,比如两个IE窗口。而对于保存在内存里的cookie,不同的浏览器有不同的处理方式 .

Cookie实际上是一小段的文本信息。客户端请求服务器,如果服务器需要记录该用户状态,就使用response向客户端浏览器颁发一个Cookie。MaxAge决定cookie的有效期,如果它是整数,在整数秒后失效,但是浏览器会将maxAge为正数的使他持久化,然后存储在对应的cookie文件中。删除cookie设置maxAge为0就行。同名的cookie,其他也相同的化会 覆盖原来的cookie,如果只有名字一样,其他不一样,是不同的cookie。

Session是在服务器上建立客户的相关信息,访问服务器时,在session中查询客户的这些信息。实现登陆可以这样做:

HttpSession session = request.getSession();       // 获取Session对象

session.setAttribute("loginTime", new Date());     // 设置Session中的属性

out.println("登录时间为:" +(Date)session.getAttribute("loginTime"));      // 获取Session属性

只有在访问jsp或者Servlet等程序时才会创建session,session会设置超时时间,过了这个时间没有访问session他就会失效。

 

session机制。session机制是一种服务器端的机制,服务器使用一种类似于散列表的结构(也可能就是使用散列表)来保存信息。

          当程序需要为某个客户端的请求创建一个session时,服务器首先检查这个客户端的请求里是否已包含了一个session标识(称为session id),如果已包含则说明以前已经为此客户端创建session,服务器就按照session id把这个session检索出来使用(检索不到,会新建一个),如果客户端请求不包含session id,则为此客户端创建一个session并且生成一个与此session相关联的session id,session id的值应该是一个既不会重复,又不容易被找到规律以仿造的字符串,这个session id将被在本次响应中返回给客户端保存。保存这个session id的方式可以采用cookie,这样在交互过程中浏览器可以自动的按照规则把这个标识发送给服务器。一般这个cookie的名字都是类似于SEEESIONID。但cookie可以被人为的禁止,则必须有其他机制以便在cookie被禁止时仍然能够把session id传递回服务器。 经常被使用的一种技术叫做URL重写,就是把session id直接附加在URL路径的后面。还有一种技术叫做表单隐藏字段。就是服务器会自动修改表单,添加一个隐藏字段,以便在表单提交时能够把session id传递回服务器.

cookie 和session 的区别:

1、cookie数据存放在客户的浏览器上,session数据放在服务器上。

2、cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗考虑到安全应当使用session。

3、session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能考虑到减轻服务器性能方面,应当使用COOKIE。

4、单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。

5、   将登陆信息等重要信息存放为SESSION
   其他信息如果需要保留,可以放在COOKIE中

转博客https://www.cnblogs.com/shiyangxt/articles/1305506.html

Cookies与Session的应用场景

登陆验证信息。一般采用Session("Logon")=true or false的形式。用户的各种私人信息,比如姓名等,某种情况下,需要保存在Session里需要在页面间传递的内容信息,比如调查工作需要分好几步。每一步的信息都保存在Session里,最后在统一更新到数据库。

cookie最典型的应用是:

 (一):判断用户是否登陆过网站,以便下次登录时能够直接登录。如果我们删除cookie,则每次登录必须从新填写登录的相关信息。

(二):另一个重要的应用是“购物车”中类的处理和设计。用户可能在一段时间内在同一家网站的不同页面选择不同的商品,可以将这些信息都写入cookie,在最后付款时从cookie中提取这些信息,当然这里面有了安全和性能问题需要我们考虑了。

登录页面:login.jsp

  <body>
    <%--本页面提供登录表单,还要显示错误信息 --%>
    <h1>登录</h1>
    <%
     String uname ="";
     Cookie[] cs = request.getCookies();
     if(cs!=null){
      for(Cookie c:cs){
       if("uname".equals(c.getName()))
       {
        uname=c.getValue();
       }
      }
     }
    %>
    <%
     String message="";
     String msg = (String)request.getAttribute("msg");
     if(msg!=null){
      message = msg;
     }
    %>
    <font color="red"><b><%=message %></b></font>
    <form action="/hellosession1/LoginServlet" method="post">
     用户名:<input type="text" name="username" value="<%=uname%>"><br>
     密 码:<input type="password" name="password"><br>
     <input type="submit" value="登录">
    </form>
  </body>

 

4,自己写:

servlet处理页面:LoginServlet.java

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  //获取表单数据
  //处理编码问题
  request.setCharacterEncoding("UTF-8");
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  //校验用户名和密码是否正确
  if(!"itcast".equalsIgnoreCase(username)){//登陆成功
   
   Cookie cookie = new Cookie("uname",username);//获取cookie
   cookie.setMaxAge(60*60*24);
   response.addCookie(cookie);
   
   HttpSession session = request.getSession();//获取session
   session.setAttribute("username", username);//向session域中存username
   response.sendRedirect("/hellosession1/session2/succ1.jsp");
  }else{//登录失败
   //如果失败,保存到request域中,转发到login.jsp
   request.setAttribute("msg", "用户名或密码错误");
   request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
  }
  
 }

 

 

登录成功页面:succ1.jsp

  <body>
   <%
      String username = (String)session.getAttribute("username");
      if(username==null){
       request.setAttribute("msg", "您还没有登录,请先登录!");
       request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
       return;
      }
     %>
    <h1>登录成功</h1>
    欢迎回来<%=session.getAttribute("username") %>
  </body>

 

 

 

自己的代码:

1,session

1)Index页面

<!-- 写session的时候直接用这个 -->

<% response.sendRedirect("/index.do"); %>

写在body中

(2)跳转

cookie与session 

3)登陆页代码

<%@ page language="java" contentType="text/html; charset=UTF-8"

    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>

<form action="login.do" method="post">

   <input type="text" name="name"/><br/>

   <input type="password" name="pwd"/><br/>

   <input type="submit" value="登陆"><br/>

</form>

</body>

</html>

4,登陆成功后代码

<%@ page language="java" contentType="text/html; charset=UTF-8"

    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>${sessionScope.user.name }登录成功!!!</h1>

 

<h2>欢迎您,${sessionScope.name }</h2>

</body>

</html>

5,后台代码

package com.cust.CS.controller;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.SessionAttributes;

import com.cust.CS.pojo.Cs;

@Controller("/console")

@SessionAttributes({"user","name"})

public class Login {

@RequestMapping("/login.do")

public String Login_l(Cs user,ModelMap map){

//user会自己注入session中

//将name放入session作用域中,这样转发页面也可以取到这个数据。

map.addAttribute("name", user.getName());

return "/loginSuccess";

}

}

 

 

2,Cookie

<%@ page language="java" contentType="text/html; charset=UTF-8"

    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>Insert title here</title>

 

 <script language="JavaScript" type="text/javascript">

 

         function addCookie(objName, objValue, objHours) {//添加cookie

             //escape() 函数可对字符串进行编码,

             var str = objName + "=" + escape(objValue);

             if (objHours > 0) {//0时不设定过期时间,浏览器关闭时cookie自动消失

                 var date = new Date();

                 var ms = objHours * 3600 * 1000;

                 date.setTime(date.getTime() + ms);

                 //expires指定了coolie的生命期

                 str += "; expires=" + date.toGMTString();

             }

             document.cookie = str;

             alert("添加cookie成功");

         }

 

         function getCookie(objName) {//获取指定名称的cookie的值

             var arrStr = document.cookie.split("; ");

             for (var i = 0; i < arrStr.length; i++) {

                 var temp = arrStr[i].split("=");

                 if (temp[0] == objName)

                     return unescape(temp[1]);

             }

         }

 

         function delCookie(name) {//为了删除指定名称的cookie,可以将其过期时间设定为一个过去的时间

             var date = new Date();

             date.setTime(date.getTime() - 10000);

             document.cookie = name + "=a; expires=" + date.toGMTString();

         }

 

         function allCookie() {//读取所有保存的cookie字符串

             var str = document.cookie;

             if (str == "") {

                 str = "没有保存任何cookie";

             }

             alert(str);

         }

 

        

         function add_() {

             var cookie_name = document.getElementById("cookie_name").value;

             var cookie_value = document.getElementById("cookie_value").value;

             var cookie_expireHours = document.getElementById("cookie_expiresHours").value;  

             addCookie(cookie_name, cookie_value, cookie_expireHours);

         }

 

         function get_() {

             var cookie_name = document.getElementById("cookie_name").value;

             var cookie_value = getCookie(cookie_name);

             alert(cookie_value);

         }

 

         function del_() {

             var cookie_name = document.getElementById("cookie_name").value;

             delCookie(cookie_name);

             alert("删除成功");

         }

    </script>

 

 

</head>

<body>

    <form name="myform" runat="server">

    <div>

        <label for="cookie_name">

            名称

        </label>

        <input type="text" id="cookie_name" name="cookie_name" runat="server" />

    </div>

    <div>

        <label for="cookie_value">

             </lable>

            <input type="text" id="cookie_value" name="cookie_value" />

    </div>

    <div>

        <label for="cookie_expireHours">

            多少个小时过期 </lable>

            <input type="text" id="cookie_expiresHours" name="cookie_expiresHours" />

    </div>

    <div>

        <input type="button" value="添加该cookie" onclick="add_()" /><input type="button" value="读取所有cookie"

            onclick="allCookie()" /><input type="button" value="读取该名称cookie" onclick="get_()" /><input

                type="button" value="删除该名称cookie" onclick="del_()" />

        <asp:Button ID="Button1" runat="server" Text="后台读取前台cookie" 

            onclick="Button1_Click1" />

    </div>

    </form>

 

  </body>

</html>