0
点赞
收藏
分享

微信扫一扫

16 域对象4 Application域

彪悍的鼹鼠 2023-03-15 阅读 75


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

 


举报

相关推荐

0 条评论