ServletDemo4.java:
package cn.edu; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* * ServletContext域 * 1.这是一个容器 * 2.ServletContext域这句话说明了容器的作用范围,也就是应用程序范围 * */ //通过ServletContext实现ServletDemo4与ServletDemo5的数据共享 public class ServletDemo4 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data="aaa"; //给整个应用的容器中上传了一个名叫data的数据 this.getServletContext().setAttribute("data", data); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
ServletDemo5.java:
package cn.edu; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletDemo5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //从ServletContext()容器中取出ServletDemo4存入的名叫data的数据 String vlaue=(String)this.getServletContext().getAttribute("data"); System.out.println(vlaue); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
时间: 2025-01-13 09:37:09