ServletContext当全局变量的使用

时间:2022-10-26 08:07:37
ServletContext对象

1,作用:JavaWeb应用的一个全局变量,一个应用只有一个ServletContext对象,在应用启动时,容器就会创建该对象

2,获得ServletContext对象的引用

3,应用ServletContext的特点,可以将该对象看做是整个web应用的总管家

4,应用

  实现多个Servlet之间的数据共享

  配置web应用的全局参数

Demo1向对象中存入参数

package com.itheima;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ServletContextDemo1 extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//获取ServletConfig对象
ServletConfig config=getServletConfig();
//根据ServletConfig对象创建ServletContext对象
ServletContext context=config.getServletContext();
//向Servletcontext对象中添加属性和属性值
context.setAttribute("abc", "你好");
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
} }

Demo2取数据

package com.itheima;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ServletContextDemo2 extends HttpServlet { @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//创建ServletContext对象
ServletContext context=getServletContext();
//得到ServletContext对象中的属性名,用Object接收
Object o=context.getAttribute("abc");
//打印
System.out.println(o);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException { } }

如果先取数据(执行Demo2),则取出的是null,如果先存数据(Demo1),则取出存入的内容。

定义全局变量

web.xml中的代码
<!-- 定义全局参数-->
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql:///test</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>123</param-value>
</context-param> //java中的获取
Enumeration name=context.getInitParameterNames();
while(name.hasMoreElements()){
System.out.println("Demo2:"+context.getInitParameter((String)name.nextElement()));
}