HTTP协议的无状态性

无状态是指,当浏览器发送请求给服务器的时候,服务器响应客户端的请求。

但是当同一个浏览器再次发送请求给了服务器的时候,服务器并不知道它就是刚才那个浏览器。

简单地说,就是服务器不回去记得你,所以就是无状态协议。

 

保存用户状态的两大机制:Session和Cookie。

 

什么是Cookie?

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

典型应用一:判定注册用户是否已经登录网站。

典型应用二:“购物车”的处理。

 

Cookie的作用:

  对特定对象的追踪

  保存用户网页浏览记录和习惯

  简化登录

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

 

JSP页面中创建与使用Cookie

创建Cookie对象

Cookie newCookie = new Cookie(String key, Object value);

写入Cookie对象

reponse.addCookie(newCookie);

读取Cookie对象

Cookie[] cookies = request.getCookie();

 

JSP中创建和使用Cookie的常用方法

方法名称

说明

void setMaxAge(int expiry)

设置cookie的有效期,以秒为单位

void setValue(String value)

在cookie创建后,对cookie进行赋值

String getName()

获取cookie的名称

String getValue()

获取cookie的值

int getMaxAge()

获取cookie的有效时间,以秒为单位

案例:实现记忆用户名和密码功能

登陆的时候会提示是否记住用户。

首先是用户的一个登陆界面login.jsp,登录界面中除了有用户名和密码,还有一个checkbox,用于提示用户是否记住用户名和密码。如果点选了这个checkbox,那么Cookie将会记住这个用户名和密码。

用户登录界面提交的表单将会传递到dologin.jsp页面中,这个页面负责Cookie相关的处理,并且将数据传递到user.jsp页面中。

这个页面需要通过login.jsp提交的表单判断checkbox是否勾选了,如果勾选了,那么我们需要设置username和password对应的cookie的生存时间为10天;如果没有勾选,则我们需要删除username和password对应的cookie。

user.jsp页面负责显示用户的用户名和密码。如果cookie保存了用户的用户名和密码,那么user.jsp页面中将会得到我的用户名和密码信息(by cookie)。

在user.jsp中我们只需要获取cookie中的信息就可以了。

<%@page import="java.net.URLDecoder"%>
<%@ 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>login page</title>
</head>
<body>
<%
    //request.setCharacterEncoding("utf-8");
    String username = "";
    String password = "";
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0)
        for (Cookie cookie : cookies)
            if (cookie.getName().equals("username"))
                username = URLDecoder.decode(cookie.getValue(), "utf-8");
            else if (cookie.getName().equals("password"))
                password = URLDecoder.decode(cookie.getValue(), "utf-8");
%>
<form name="regForm" action="dologin.jsp" method="post">
<table>
  <tr>
    <td>用户名:</td>
    <td><input type="text" name="username" value="<%=username %>"></td>
  </tr>
  <tr>
    <td>密码:</td>
    <td><input type="password" name="password" value="<%=password %>"></td>
  </tr>
  <tr>
    <td colspan="2"><input type="checkbox" name="isUseCookie" value="tenDays">十天内记住用户名和密码</td>
  </tr>
  <tr>
    <td colspan="2"><input type="submit" value="提交"></td>
  </tr>
</table>
</form>
</body>
</html>
login.jsp

相关文章:

  • 2021-06-28
  • 2021-05-26
  • 2021-08-10
  • 2021-07-15
  • 2021-08-05
  • 2021-10-18
猜你喜欢
  • 2021-07-29
  • 2021-04-17
  • 2021-11-23
  • 2021-08-10
  • 2022-01-11
  • 2021-12-19
  • 2021-11-21
相关资源
相似解决方案