Application域
有效范围
当前web服务内,跨请求,跨会话
生命周期
创建 项目启动
使用 项目运行任何时间有效
销毁 项目关闭
测试代码
Application域中放入数据
package com.msb.testApplication; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * @Author: Ma HaiYang * @Description: MircoMessage:Mark_7001 */ @WebServlet(urlPatterns = "/addToApplication.do") public class Servlet1 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 向Application域中添加数据 ServletContext application = req.getServletContext(); List<String> x=new ArrayList<>(); Collections.addAll(x, "a","b","c"); application.setAttribute("list", x); application.setAttribute("gender","girl"); application.setAttribute("name","晓明"); } }
Application域中读取数据
package com.msb.testApplication; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.List; /** * @Author: Ma HaiYang * @Description: MircoMessage:Mark_7001 */ @WebServlet(urlPatterns="/readFromApplication.do") public class Servlet2 extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext application = this.getServletContext(); // 从application域中读取数据 List<String> list =(List<String>) application.getAttribute("list"); System.out.println(list); System.out.println(application.getAttribute("gender")); System.out.println(application.getAttribute("name")); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了