ServletContext对象的应用场景

ServletContext对象在WEB容器(Tomcat)启动时,它会被自动创建,它代表着当前应用。当我们停止服务器或者删除Web应用时,对象就会被销毁。

获取这个对象引用的方式用两种:
1)由于GenericServlet这个对象封装了获取的方法,所以可以直接调用this.getServletContext()这个方法得到其引用。
2)由于ServletConfig对象中维护了其引用,所以也可以这样得到其引用:this.getServletConfig().getServletContext()。

ServletContext对象被称之为Context域对象,当前web应用中的所有Servlet都共享此对象,所以多个Servlet可以通过这个对象实现数据共享。

我们可以在web.xml文件中通过配置context-param这个元素来指定一些所有Servlet共有的一些信息,for example:数据库的连接信息。如果我们把这个信息通过Servlet来配置,那么我们不得不在每个Servlet元素里面指定这些初始化信息,而通过context-param这个元素指定一些初始化信息就可以很容易的解决这个问题。

我们可以把一些公共的数据封装到这个对象之中,但是我们不能通过这个对象把数据带到Jsp页面,如果这样的话会产生线程安全问题。假设当有很多用户访问同一个Servlet时,如果把从数据库取得的信息封装到这个对象中并带到jsp页面,那么就有可能出现第一个用户看到的数据是第二个用户的,所以我们不能把数据通过这个对象来传递。

ServletContext可以很方便的读取象xml文件或者properties文件这样的资源。下面的代码很好的说明了这点:

public class ServletDemo extends HttpServlet {
	@Override
	public void service(ServletRequest req, ServletResponse res)
			throws ServletException, IOException {
		Properties dbProperties = new Properties();
		//利用ServletContext可以很容易把应用中的资源关联到流上
		InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/jdbc.properties");
		dbProperties.load(in);
		String dburl = dbProperties.getProperty("jdbcUrl");
		System.out.println(dburl);
	}
}


但是,如果一个真正的项目数据库的访问信息不可能在Servlet中去写,而是在Dao中,那么我们如何去加载一些资源呢?下面的代码可以解决这个问题:

public class UserDAO {
	public void delete() throws IOException {
		//通过类获得这个类的字节码然后搞到类加载器
		ClassLoader classLoader = UserDAO.class.getClassLoader();
		
		Properties dbProperties = new Properties();
		InputStream in = classLoader.getResourceAsStream("jdbc.properties");
		dbProperties.load(in);
		
		String dburl = dbProperties.getProperty("jdbcUrl");
		System.out.println(dburl);
	}
}

上面的代码我们也可以通过静态代码块来加载这一资源文件,但是,要注意的是,加载后的资源如果被修改了,那么属性值还是以前的。

你可能感兴趣的:(作用域,servletContext,加载资源)