16 域对象4 Application域

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

 

posted @ 2023-03-15 08:25  CodeWhisperer001  阅读(6)  评论(0编辑  收藏  举报