• Java遇见HTML——JSP篇之JSP状态管理


    一、http协议的无状态

    无状态性是指,当浏览器发送请求给服务器的时候,服务器响应客户端请求。
    但是当同一个浏览器再次发送请求给服务器的时候,服务器并不知道他就是刚才的那个浏览器。
    简单的说,就是服务器不会去记得你,所以就是无状态协议。

    既然http是一种无状态的传输协议,无法记录用户的状态,就要想办法保存用户的状态。

    那么,如何保护用户状态呢?

    保护用户状态的两大机制:

    第一种方法:用JSP的九大内置对象之一Session。

    第二种:就是一种客户端技术:Cookie

    二、Cookie概述  

    Cookie:中文名称为“小甜饼”,是Web服务器保存在客户端的一系列文本信息。

    Cookie的作用

    • 对特定对象的追踪
    • 保存用户网页浏览记录与习惯
    • 监护登录

    安全风险:容易泄露用户信息。

    三、JSP页面中创建与使用Cookie

    常用方法:

    注意:getValue()和setValue()返回或者传参都是字符串类型,因为上面已经说过Cookie是“Web服务器保存在客户端的一系列文本信息”,是以文本文件形式保存在客户端的。保存的cookie对象从本质而言就是字符串,所以在赋值或者取值的时候添加的参数以及获取到的值都是字符串类型。

    四、案例:Cookie在登录中的应用

     代码:

    login.jsp

     1 <%@page import="java.net.URLDecoder"%>
     2 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
     3 <%
     4 String path = request.getContextPath();
     5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     6 %>
     7 
     8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     9 <html>
    10   <head>
    11     <base href="<%=basePath%>">
    12     
    13     <title>My JSP 'index.jsp' starting page</title>
    14     <meta http-equiv="pragma" content="no-cache">
    15     <meta http-equiv="cache-control" content="no-cache">
    16     <meta http-equiv="expires" content="0">    
    17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    18     <meta http-equiv="description" content="This is my page">
    19     <!--
    20     <link rel="stylesheet" type="text/css" href="styles.css">
    21     -->
    22   </head>
    23   
    24   <body>
    25   <%
    26           request.setCharacterEncoding("utf-8");
    27         String userName="";
    28         String passWord="";
    29         Cookie[] cookies=request.getCookies();
    30             if(cookies !=null && cookies.length>0){
    31                 for(Cookie c:cookies){
    32                     if(c.getName().equals("userName")){
    33                         userName=URLDecoder.decode(c.getValue(), "utf-8");//URLDecoder解码
    34                     }
    35                     if(c.getName().equals("passWord")){
    36                         passWord=URLDecoder.decode(c.getValue(), "utf-8");//URLDecoder解码
    37                     }
    38                 }
    39             }
    40      %>
    41     <form name="loginForm" action="doLogin.jsp" method="post">
    42         <table>
    43             <tr>
    44                 <td>用户名:</td>
    45                 <td><input type="text" name="userName" value="<%=userName%>"></td><!-- 如果有cookie,会显示上次保存的数据 -->
    46             </tr>
    47             <tr>
    48                 <td>密码:</td>
    49                 <td><input type="password" name="passWord" value="<%=passWord %>"></td>
    50             </tr>
    51             <tr>
    52                 <td colspan="2"><input type="checkbox" name="isUseCookie" checked="checked">十天记住我的登录状态</td>
    53             </tr>
    54             <tr>
    55                 <td align="center"><input type="submit" value="登录"></td>
    56                 <td align="center"><input type="reset" value="取消"></td>
    57             </tr>
    58         </table>
    59     </form>
    60   </body>
    61 </html>
    View Code

    doLogin.jsp

     1 <%@page import="java.net.URLEncoder"%>
     2 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     3 <%
     4 String path = request.getContextPath();
     5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     6 %>
     7 
     8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
     9 <html>
    10   <head>
    11     <base href="<%=basePath%>">
    12     
    13     <title>My JSP 'doLogin.jsp' starting page</title>
    14     
    15     <meta http-equiv="pragma" content="no-cache">
    16     <meta http-equiv="cache-control" content="no-cache">
    17     <meta http-equiv="expires" content="0">    
    18     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    19     <meta http-equiv="description" content="This is my page">
    20     <!--
    21     <link rel="stylesheet" type="text/css" href="styles.css">
    22     -->
    23 
    24   </head>
    25   
    26   <body>
    27     <h1>登陆成功!</h1>
    28     <br>
    29     <br>
    30     <%
    31         request.setCharacterEncoding("utf-8");//32         //首先判断用户是否选择了记住登录状态
    33         String[] isUseCookie=request.getParameterValues("isUseCookie");
    34         if(isUseCookie !=null && isUseCookie.length>0){
    35             //把用户名和密码保存在Cookie对象里
    36             /* String userName=request.getParameter("userName");//如果输入中文后台会报错,需要加上①②
    37             String passWord=request.getParameter("passWord"); */
    38             //使用URLEncoder解决无法在Cookie当中保存中文字符串的问题
    39             String userName=URLEncoder.encode(request.getParameter("userName"), "utf-8");//40             String passWord=URLEncoder.encode(request.getParameter("passWord"),"utf-8");
    41             Cookie userNameCookie=new Cookie("userName",userName);
    42             Cookie passWordCookie=new Cookie("passWord",passWord);
    43             userNameCookie.setMaxAge(864000);
    44             passWordCookie.setMaxAge(864000);//设置最大生存期限为10天
    45             response.addCookie(userNameCookie);
    46             response.addCookie(passWordCookie);
    47         }else{
    48             Cookie[] cookies=request.getCookies();
    49             if(cookies !=null && cookies.length>0){
    50                 for(Cookie c:cookies){
    51                     if(c.getName().equals("userName") || c.getName().equals("passWord")){
    52                         c.setMaxAge(0);//设置Cookie失效
    53                         response.addCookie(c);//重新保存
    54                     }
    55                 }
    56             }
    57         }
    58      %>
    59     <a href="user.jsp" target="_blank">查看用户信息</a>
    60   </body>
    61 </html>
    View Code

    user.jsp

     1 <%@page import="java.net.URLDecoder"%>
     2 <%@page import="java.net.URLEncoder"%>
     3 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
     4 <%
     5 String path = request.getContextPath();
     6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
     7 %>
     8 
     9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    10 <html>
    11   <head>
    12     <base href="<%=basePath%>">
    13     
    14     <title>My JSP 'user.jsp' starting page</title>
    15     
    16     <meta http-equiv="pragma" content="no-cache">
    17     <meta http-equiv="cache-control" content="no-cache">
    18     <meta http-equiv="expires" content="0">    
    19     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    20     <meta http-equiv="description" content="This is my page">
    21     <!--
    22     <link rel="stylesheet" type="text/css" href="styles.css">
    23     -->
    24 
    25   </head>
    26   
    27   <body>
    28     <h1>用户信息</h1>
    29     <hr>
    30     <br>
    31     <br>
    32     <%
    33            request.setCharacterEncoding("utf-8");
    34         String userName="";
    35         String passWord="";
    36         Cookie[] cookies=request.getCookies();
    37             if(cookies !=null && cookies.length>0){
    38                 for(Cookie c:cookies){
    39                     if(c.getName().equals("userName")){
    40                         /* userName=c.getValue(); */
    41                         userName=URLDecoder.decode(c.getValue(), "utf-8");//URLDecoder解码
    42                     }
    43                     if(c.getName().equals("passWord")){
    44                         /* passWord=c.getValue(); */
    45                         passWord=URLDecoder.decode(c.getValue(), "utf-8");
    46                     }
    47                 }
    48             }
    49      %>
    50     用户名:<%=userName %><br>
    51     密码:<%=passWord %><br>
    52   </body>
    53 </html>
    View Code

    运行结果:

    具体分析:

    1、在login.jsp中使用checkbox来记录用户是否需要保存cookies
    2
    、在dologin页面进行cookies是否需要被保存的判定。
    1)通过request.getParamter()获取填写的用户名和密码;
    2)将获取的用户名和密码保存在cookie中;
    Cookie usernameCookie = new Cookie("username",username); [
    键值对形式]
    ......
    3)将cookie保存在浏览器中。
    使用response.addCookie(usernameCookie);
    同时设置cookie的有效期:
    使用usernameCookie.setMaxAge(648000); [单位为秒]

    3
    、在登录成功后的用户界面调用cookie显示用户名和密码。(将客户端保存的cookie保存在数组中,然后赋值给字符串后用来输出显示)
    4
    、保存中文cookie需要进行编码和解码,需要引入javanet包。(添加cookie时编码URLEncode,读取cookie后解码URLDecode
    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");
    }
    }

    ps:java.net包中:
    URLEncoder.encode();
    字符编码工具类
    URLDecoder.decode();
    字符解码工具类

     

    cookie在登录过程中出现的乱码问题解决方式
    a:
    在对应页面中导入java.net.*包,并将相应的字符用转码URLEncode.encodeString,要转的编码)
    b.
    在对应页面中导入java.net.*包,并将相应的字符用编码解码URLDecode.decode(String ,解码用的编码)

    五、Session与Cookie的对比

    即:

    1、保存位置:session在服务器端内存,cookie在客户端文本
    2
    、保存对象:session保存Object类,cookie保存String
    3
    、生存权:session会话结束即销毁,cookie可以长期保存在客户端
    4
    、重要性:session安全性更高,保存重要信息,cookie保存不重要的信息

    ps:

    Cookie中对保存对象的大小是有限制的.Session可以保存任意大小的的对象类型。

  • 相关阅读:
    IIS和ASP.NET2.0
    VS.NET里关于不能够使用向导的问题
    CodeFile
    判断一个字符串是否全是数字的多种方法及其性能比较(C#实现)
    托管和非托管资源
    ASP.NET 2.0页面框架的几处变化
    导出QQWry.Dat中IP地址到文件[C#]
    面向对象在数据库应用程序中的应用(dotNet)
    如何取得IP/用户名等信息
    验证Email是否真正存在(上)
  • 原文地址:https://www.cnblogs.com/Qian123/p/5281551.html
Copyright © 2020-2023  润新知