Servlet之ServletContext、Session、Cookie

简介:

ServletContext、Session、Cookie都可以用于存储数据,不过三者存储数据的位置及作用域不同。

这里写图片描述

由上图我们可以看出
ServletContext存储于服务端,每个客户端都可以访问到,数据共享。
Session存储于服务端,每个客户端有自己独立的数据区域。
Cookie存储于客户端。

下面通过代码来看一下三者的用法

package com.gujin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContextServlet extends HttpServlet
{
   @Override
   protected void doGet(HttpServletRequest req, HttpServletResponse response)
         throws ServletException, IOException
   {
      ServletContext context = this.getServletConfig()
               .getServletContext();
      Integer count = (Integer) context.getAttribute("visit_count");
      if (count == null)
      {
         count = 1;
      }
      else
      {
         count++;
      }
      context.setAttribute("visit_count", count);
      // 设置响应内容类型
      response.setContentType("text/html;charset=UTF-8");

      PrintWriter writer = response.getWriter();
      // 想输出流写的内容就是客户端接收到的内容
      writer.print("<html>");
      writer.print("<head>");
      writer.print("<meta charset='UTF-8'>");
      writer.print("</head>");
      writer.print("<body>");
      writer.print(MessageFormat.format("<h1>访问次数:{0}</h1>", count));
      writer.print("</body>");
      writer.print("<html>");
      writer.flush();
      writer.close();
   }
}
package com.gujin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionServlet extends HttpServlet
{
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
   {
      String flag = request.getParameter("flag");
      HttpSession session = request.getSession();
      if ("login".equals(flag))
      {
         session.setAttribute("login", "login");
      }
      else if ("logout".equals(flag))
      {
         session.removeAttribute("login");
      }

      PrintWriter writer = response.getWriter();
      // 想输出流写的内容就是客户端接收到的内容
      writer.print("<html>");
      writer.print("<head>");
      writer.print("<meta charset='UTF-8'>");
      writer.print("</head>");
      writer.print("<body>");
      writer.print(MessageFormat.format("<h1>{0}</h1>",
            session.getAttribute("login") == null ? "未登录" : "已登录"));
      writer.print("</body>");
      writer.print("<html>");
      writer.flush();
      writer.close();
   }
}
package com.gujin.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServlet extends HttpServlet
{
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
   {
      // 设置响应内容类型
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter writer = response.getWriter();
      // 想输出流写的内容就是客户端接收到的内容
      writer.print("<html>");
      writer.print("<head>");
      writer.print("<meta charset='UTF-8'>");
      writer.print("</head>");
      writer.print("<body>");
      writer.print("<ul>");

      // 获得所有Cookie
      Cookie[] cookies = request.getCookies();
      if (cookies != null)
      {
         for (Cookie cookie : cookies)
         {
            writer.print(MessageFormat.format("<li>{0}:{1}</li>",
                  cookie.getName(), cookie.getValue()));
         }
      }
      Cookie cookie = new Cookie("CookieServlet", System.currentTimeMillis() + "");
      //添加Cookie
      response.addCookie(cookie);
      writer.print("</ul>");
      writer.print("</body>");
      writer.print("<html>");
      writer.flush();
      writer.close();
   }
}

然后在web.xml中进行配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Servlet</display-name>
  <servlet>
    <servlet-name>context</servlet-name>
    <servlet-class>com.gujin.servlet.ContextServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>context</servlet-name>
    <url-pattern>/context</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>session</servlet-name>
    <servlet-class>com.gujin.servlet.SessionServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>session</servlet-name>
    <url-pattern>/session</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>cookie</servlet-name>
    <servlet-class>com.gujin.servlet.CookieServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>cookie</servlet-name>
    <url-pattern>/cookie</url-pattern>
  </servlet-mapping>
</web-app>
目录
相关文章
|
4天前
|
存储 前端开发 Java
JavaWeb基础7——会话技术Cookie&Session
会话技术、Cookie的发送和获取、存活时间、Session钝化与活化、销毁、用户登录注册“记住我”和“验证码”案例
JavaWeb基础7——会话技术Cookie&Session
|
22天前
|
存储 JavaScript 前端开发
Cookie 反制策略详解:Cookie加解密原理、Cookie和Session机制、Cookie hook、acw_sc__v2、jsl Cookie调试、重定向Cookie
Cookie 反制策略详解:Cookie加解密原理、Cookie和Session机制、Cookie hook、acw_sc__v2、jsl Cookie调试、重定向Cookie
39 1
|
24天前
|
存储 安全 搜索推荐
【JavaWeb 秘籍】Cookie vs Session:揭秘 Web 会话管理的奥秘与实战指南!
【8月更文挑战第24天】本文以问答形式深入探讨了Web开发中关键的会话管理技术——Cookie与Session。首先解释了两者的基本概念及工作原理,随后对比分析了它们在存储位置、安全性及容量上的差异。接着,通过示例代码详细介绍了如何在JavaWeb环境中实现Cookie与Session的操作,包括创建与读取过程。最后,针对不同应用场景提供了选择使用Cookie或Session的指导建议,并提出了保障二者安全性的措施。阅读本文可帮助开发者更好地理解并应用这两种技术。
28 1
|
28天前
|
存储 安全 搜索推荐
深入探讨Session和Cookie的概念、用途以及如何在Java Web开发中有效地使用它们进行用户状态管理。
在Java Web开发中,Session和Cookie是管理用户状态的核心技术。Session存储于服务器端,通过唯一的Session ID识别用户,确保数据安全与隐私;Cookie则存储于客户端,用于记录用户偏好等信息。两者各有优势:Session适合存储敏感数据,但需合理管理避免资源浪费;Cookie便于持久化存储,但在安全性上需谨慎设置。开发者可通过Servlet API轻松操作二者,实现个性化用户体验与应用性能优化。
25 2
|
28天前
|
存储 缓存 安全
Cookie和Session
【8月更文挑战第20天】
15 1
|
1月前
|
存储 JSON JavaScript
震撼!Cookie、Session、Token、JWT 终极对决:揭开 Web 认证的神秘面纱!
【8月更文挑战第13天】Web 开发中,Cookie、Session、Token 和 JWT 常混淆。Cookie 是服务器给客户端的小信息片,如登录状态,每次请求都会返回。Session 则是服务器存储的用户数据,通过 Session ID 追踪。Token 类似通行证,证明客户端身份且可加密。JWT 是结构化的 Token,含头部、载荷及签名,确保数据完整性和安全性。
39 4
|
17天前
|
C# 开发者 Windows
WPF遇上Office:一场关于Word与Excel自动化操作的技术盛宴,从环境搭建到代码实战,看WPF如何玩转文档处理的那些事儿
【8月更文挑战第31天】Windows Presentation Foundation (WPF) 是 .NET Framework 的重要组件,以其强大的图形界面和灵活的数据绑定功能著称。本文通过具体示例代码,介绍如何在 WPF 应用中实现 Word 和 Excel 文档的自动化操作,包括文档的读取、编辑和保存等。首先创建 WPF 项目并设计用户界面,然后在 `MainWindow.xaml.cs` 中编写逻辑代码,利用 `Microsoft.Office.Interop` 命名空间实现 Office 文档的自动化处理。文章还提供了注意事项,帮助开发者避免常见问题。
48 0
|
2月前
|
存储 安全 搜索推荐
Cookie和Session的区别,99%的程序员都不知道的细节!
大家好,我是小米,在Web开发中,Cookie和Session是两种重要的状态管理工具。它们有着不同的存储位置、安全性和应用场景。本篇文章将详细解析它们的区别和应用,让你在开发过程中能够更加游刃有余。让我们一起深入了解吧!
53 1
|
1月前
Error unprotecting the session cookie.The key {...} was not found in the key ring.
Error unprotecting the session cookie.The key {...} was not found in the key ring.
48 0
|
1月前
Error unprotecting the session cookie.The payload was invalid.
Error unprotecting the session cookie.The payload was invalid.
51 0