什么是域对象?
域对象,是可以像 Map 一样存取数据的对象,叫域对象。
这里的域指的是存取数据的操作范围,整个 web 工程。
存数据 取数据 删除 数据
Map put() get() remove()
域对象 setAttribute() getAttribute() removeAttribute();
ServletContext 像 Map 一样存取数据:
package top.qaqaq.P134; /**
* @author RichieZhang
* @create 2022-12-05 下午 1:36
*/
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
public class ContextServlet1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
什么是域对象?
域对象,是可以像 Map 一样存取数据的对象,叫域对象。
这里的域指的是存取数据的操作范围,整个 web 工程。
存数据 取数据 删除 数据
Map put() get() remove()
域对象 setAttribute() getAttribute() removeAttribute();
*/
// 获取ServletContext对象
ServletContext context = getServletContext();
System.out.println(context);
System.out.println("保存之前:Context1 获取key1的值是:" + context.getAttribute("key1"));
context.setAttribute("key1","value1");
System.out.println("Context1 中获取域数据key1的值是:" + context.getAttribute("key1"));
System.out.println("Context1 中获取域数据key1的值是:" + context.getAttribute("key1"));
System.out.println("Context1 中获取域数据key1的值是:" + context.getAttribute("key1"));
System.out.println("Context1 中获取域数据key1的值是:" + context.getAttribute("key1"));
System.out.println("Context1 中获取域数据key1的值是:" + context.getAttribute("key1"));
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
package top.qaqaq.P134; /**
* @author RichieZhang
* @create 2022-12-05 下午 1:45
*/
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import java.io.IOException;
public class ContextServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context = getServletContext();
System.out.println(context);
System.out.println("Context2 中获取域数据key1的值是:" + context.getAttribute("key1"));
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<servlet>
<servlet-name>ContextServlet1</servlet-name>
<servlet-class>top.qaqaq.P134.ContextServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextServlet1</servlet-name>
<url-pattern>/context1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ContextServlet2</servlet-name>
<servlet-class>top.qaqaq.P134.ContextServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextServlet2</servlet-name>
<url-pattern>/context2</url-pattern>
</servlet-mapping>