获得ServletContext对象方法方法一:this.getServletConfig().getServletContect();方法二:this.GetServletContext();ServletContext域说明它是一个容器,这个域的作用范围是整个应用程序范围,可以实现多个Servlet的数据共享吗,例如demo6中向servlet对象中写入了参数名为data值为hello的数据,在demo7中对写入servletContext的数据读取,实现了两个servlet之间的数据共享
package servlet.thread;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.getServletContext().setAttribute("data", "hello");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
package servlet.thread;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Demo7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(this.getServletContext().getAttribute("data"));;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
在配置文件中,可以为整个web应用配置初始化参数<context-param><param-name>data</param-name><param-value>data</param-value></context-param>在某个servlet中可以直接使用ServletContext对象读取配置参数
资源文件的两种形式:properties和xml,关系型数据用xml文件配置
得到properties文件中参数值的方法
InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
java.util.Properties props=new java.util.Properties();
props.load(in);
String name=props.getProperty("userName");
一个普通类即非Servlet类,需要用类加载器加载资源文件,但是文件不能太大