当前位置 : 主页 > 编程语言 > java >

16 域对象4 Application域

来源:互联网 收集:自由互联 发布时间:2023-03-22
Application域 有效范围 当前web服务内,跨请求,跨会话 生命周期 创建 项目启动 使用 项目运行任何时间有效 销毁 项目关闭 测试代码 Application域中放入数据 package com.msb.testApplication;import

 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")); }}

 

上一篇:5 Cookie和Session案例开发
下一篇:没有了
网友评论