JSP中创建与使用Cookie

  创建Cookie对象

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

  写入Cookie对象

    response.addCookie(newCookie);

  读取Cookie对象

    Cookie[] cookies = request.getCookies();

  常用方法

    void setMaxAge(int expiry)  设置cookie有效期,单位-秒

    void setValues(String value)    对cookie进行赋值

    String getName()       获取cookie的名称

    String getValue()       获取cookie的值

    int getMaxAge()        获取cookie有效时间,单位-秒

通过Cookie实现登录状态记录,示例代码:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="java.net.HttpCookie" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<!-- Page title -->
<title>imooc - Login</title>
<!-- End of Page title -->
<!-- Libraries -->
<link type="text/css" href="css/login.css" rel="stylesheet" />
<link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/easyTooltip.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<!-- End of Libraries -->
</head>
<body>
<%
String username = "";
String password = "";
Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
for(Cookie c:cookies){
if(c.getName().equals("username")){
username = c.getValue();
}
if(c.getName().equals("password")){
password = c.getValue();
}
}
}
%>
<div id="container">
<div class="logo">
<a href="#"><img src="assets/logo.png" alt="" /></a>
</div>
<div id="box">
<form action="do_login.jsp" method="post">
<p class="main">
<label>用户名: </label>
<input name="username" value="<%=username%>" />
<label>密码: </label>
<input type="password" name="password" value="<%=password%>"> </p> <p class="space">
<label>7天免登陆</label>
<input type="checkbox" name="isUseCookie" checked="checked">
<input type="submit" value="登录" class="login" style="cursor: pointer;"/>
</p>
</form>
</div>
</div>
</body>
</html>

HTML-Login.jsp

<%@ page contentType="text/html;charset=UTF-8" %>
<jsp:useBean id="loginUser" class="com.po.Users" />
<jsp:useBean id="userDAO" class="com.dao.UsersDAO" />
<jsp:setProperty name="loginUser" property="*" /> <%
// 如果用户名和密码都等于admin,则登录成功
if(userDAO.usersLogin(loginUser)){
session.setAttribute("loginUser", loginUser.getUsername());
request.getRequestDispatcher("login_success.jsp").forward(request, response);
}else {
response.sendRedirect("login_failure.jsp");
}
%>

HTML-doLogin.jsp

<%@ page import="java.net.HttpCookie" %><%--
Created by IntelliJ IDEA.
User: shongbing
Date: 2019-01-05
Time: 14:10
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<!-- Page title -->
<title>imooc - Login</title>
<!-- End of Page title -->
<!-- Libraries -->
<link type="text/css" href="css/login.css" rel="stylesheet" />
<link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/easyTooltip.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<!-- End of Libraries -->
</head>
<body>
<div id="container">
<div class="logo">
<a href="#"><img src="assets/logo.png" alt="" /></a>
</div>
<div id="box">
<%
String loginUser = "";
if(session.getAttribute("loginUser") != null){
loginUser = session.getAttribute("loginUser").toString();
} String[] isUseCookies = request.getParameterValues("isUseCookie");
if(isUseCookies != null && isUseCookies.length >0){
// 把用户名和密码保存在Cookie对象中
String username = request.getParameter("username");
String password = request.getParameter("password");
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); // 设置Cookie失效
response.addCookie(c); // 重新保存
}
}
}
}
%>
<a href="users.jsp" target="_blank">登录成功,查看用户信息</a>
</div>
</div>
</body>
</html>

HTML-LoginSuccess.jsp

<%@ page import="java.net.HttpCookie" %><%--
Created by IntelliJ IDEA.
User: shongbing
Date: 2019-01-06
Time: 12:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户信息</title>
</head>
<body>
<h1>用户信息</h1><hr>
<%
String username = "";
String password = "";
Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
for(Cookie c:cookies){
if(c.getName().equals("username")){
username = c.getValue();
}
if(c.getName().equals("password")){
password = c.getValue();
}
}
}
%>
Username: <%=username %><br>
Password: <%=password %><br> </body>
</html>

HTML-UserInfo.jsp

JSP Cookie状态管理的更多相关文章

  1. 状态管理之cookie使用及其限制、session会话

    # 1.什么是状态管理? 将浏览器与web服务器之间多次交互当作一个整体来处理,并且将多次交互所涉及的数据(即状态)保存下来.(cookie浏览器所涉及到的访问数据保存下来)# 2.如何进行状态管理? ...

  2. Unit06: 状态管理-cookie

    Unit06: 状态管理-cookie web package web; import java.io.IOException; import java.io.PrintWriter; import ...

  3. [原创]java WEB学习笔记28: 会话与状态管理Cookie 机制

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  4. HTTP状态管理机制之Cookie

    一.cookie 起源 cookie 最早是网景公司的雇员 Lou Montulli 在1993年3月发明,后被 W3C 采纳,目前 cookie 已经成为标准,所有的主流浏览器如 IE.Chrome ...

  5. [Asp.Net]状态管理(ViewState、Cookie)

    简介 HTTP协议是无状态的.从客户端到服务器的连接可以在每个请求之后关闭.但是一般需要把一些客户端信息从一个页面传送给另一个页面. 无状态的根本原因是:浏览器和服务器使用Socket通信,服务器将请 ...

  6. 状态管理cookie 案例

    1状态管理:服务器为了追踪同一个客户端发出的请求,将多次交互看成一个整体看待 2:cookie的生存时间,默认情况下,cookie保存在浏览器内存中,只要不关闭浏览器,cookie就一直存在 如果希望 ...

  7. 转载ASP.NET 状态管理Application,Session,Cookie和ViewState用法

    转载原地址 http://www.cnblogs.com/cuishao1985/archive/2009/09/24/1573403.html ASP.NET状态管理 APPlication,Ses ...

  8. HTTP状态管理机制之Cookie(转)

    一.cookie 起源 cookie 最早是网景公司的雇员 Lou Montulli 在1993年3月发明,后被 W3C 采纳,目前 cookie 已经成为标准,所有的主流浏览器如 IE.Chrome ...

  9. 基于cookie的用户登录状态管理

    cookie是什么 先来花5分钟看完这篇文章:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Cookies 看完上文,相信大家对cookie已经有 ...

随机推荐

  1. audio的总结

    H5的audio谁都会用, 照着官方api放个标签, play, stop... 实际运用中需要一些兼容性封装: //audio $.audio = function(params) { var $a ...

  2. Building Shops

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others) Total Submissi ...

  3. H - N皇后问题

    H - N皇后问题 Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u Descripti ...

  4. IDEA中的lombok插件安装以及各注解的详细介绍

    IDEA中的lombok插件安装以及各注解的详细介绍 其实对于我们来说, 写好实体类后,直接用快捷方式生成get,set方法,还有 构造方法就行了,但是对于字段比较多的, 如果修改一个属性的话,就要再 ...

  5. 第七课 nodejs请求响应

    1 server.js 接收请求接收请求参数 和接收完成需要对request增加两个监听事件 var http = require('http');var url = require('url');f ...

  6. 路径规划 Adjacency matrix 传球问题

    建模 问题是什么 知道了问题是什么答案就ok了 重复考虑 与 重复计算 程序可以重复考虑  但往目标篮子中放入时,放不放把握好就ok了. 集合 交集 并集 w 路径规划 字符串处理 42423 424 ...

  7. 进程 query foreach

    http://php.net/manual/en/pdo.query.php PDO::query() executes an SQL statement in a single function c ...

  8. RemoveDuplicatesfromSortedArray

    Given a sorted array, remove the duplicates in place such that each element appear only once and ret ...

  9. spring 编译时抱错纪录class path resource [spring/] cannot be resolved to URL because it does not exist

    class path resource [spring/] cannot be resolved to URL because it does not exist; 在 pom.xml 里添加如下代码 ...

  10. C++程序设计练习(一)

    // 1. 在屏幕上输出内容 #include<iostream> using namespace std; int main(){ int i= 1; cout<<" ...