Servlet多个对象共享数据

一个Web应用中的所有Servlet,共享同一个ServletContext对象
因此,ServletContext对象的域属性,可以被该Web应用中的所用Servlet访问
在ServletContext接口中,定义了分别用于增加、删除、设置ServletContext域属性的4个方法
ServletContext接口的方法

Enumeration getAttributeNames()

返回一个Enumeration对象,该对象包含所有存放在ServletContext中的所有域属性名

Object getAttribute(String name)

根据参数指定的属性名,返回一个与之匹配的域属性值

Void removeAttribute(String name)

根据参数指定的域属性名,从ServletContext中删除匹配的域属性

Void setAttribute(String name,Object obj)

设置ServletContext的域属性,name是域属性名,obj是域属性值
实例程序
编写TestServlet04类

package cn.itcast.chapter04.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet04 extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
ServletContext context=this.getServletContext();
//通过setAttribute()方法设置属性值
context.setAttribute("data","this servlet save data");
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
this.doGet(request,response);
}
}

setAttribute()方法,用于设置ServletContext对象的属性值

编写TestServlet05类

package cn.itcast.chapter04.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet05 extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
PrintWriter out=response.getWriter();
ServletContext context=this.getServletContext();
//通过getAttribute()方法获取属性值
String data=(String)context.getAttribute("data");
out.println(data);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
this.doGet(request,response);
}
}

getAttribute()方法,用于获取ServletContext对象的属性值
编写web.xml文件


<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0">
<servlet>
        <servlet-name>TestServlet04servlet-name>
        <servlet-class>cn.itcast.chapter04.servlet.TestServlet04servlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>TestServlet04servlet-name>
        <url-pattern>/TestServlet04url-pattern>
servlet-mapping>
<servlet>
        <servlet-name>TestServlet05servlet-name>
        <servlet-class>cn.itcast.chapter04.servlet.TestServlet05servlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>TestServlet05servlet-name>
        <url-pattern>/TestServlet05url-pattern>
servlet-mapping>
web-app>

启动Tomcat,在浏览器中输入
http://localhost:8080/chapter04/TestServlet04
访问TestServlet04,将数据存入ServletContext对象
然后,输入地址
http://localhost:8080/chapter04/TestServlet05
访问TestServlet05
显示结果如下
Servlet多个对象共享数据_第1张图片

你可能感兴趣的:(————Servlet,【SSH】)