ServletContext对象学习

1,WEB容器在启动时,它会为每一个WEB应用程序都建立一个对应的ServletContext对象,它表明当前web应用。html

2,ServletConfig对象中维护了ServletContext对象的引用,开发人员在编写servlet时,能够经过ServletConfig.getServletContext方法得到ServletContext对象java

代码:(经过context-param标签为整个web应用配置初始化参数)
mysql

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  
  <context-param>
  	<param-name>name</param-name>
  	<param-value>zxx</param-value>
  </context-param>
  
  <context-param>
  	<param-name>url</param-name>
  	<param-value>jdbc:mysql://localhost:3306/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>root</param-value>
  </context-param>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

1,代码(获取上下文);web

//获取servletContext对象
public class ContextDemo1 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 通過ServletConfig對象得到上下文
		this.getServletConfig().getServletContext();

		// 也能够直接获取
		this.getServletContext();

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


ServletContext应用sql

1,获取web应用的初始化参数:app

代码:jsp

//获取web应用初始化参数
public class ContextDemo4 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Enumeration e = this.getServletContext().getInitParameterNames();
		while(e.hasMoreElements()){
			String name = (String) e.nextElement();
			String value = this.getServletContext().getInitParameter(name);
			System.out.println(name + "=" + value);
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


2,在多个servlet之间共享数据:this

代码1(往上下文中存入数据):url

//经过ServletContext共享数据
public class ContextDemo2 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String data = "aaaaaa";
		//给上下文设置数据
		this.getServletContext().setAttribute("data", data);
		
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

代码2(从上下文中取出数据):spa

public class ContextDemo3 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//从上下文中取出数据
		String data = (String) this.getServletContext().getAttribute("data");
		System.out.println(data);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


3,实现Servlet的转发:

//实现请求转发
public class ContextDemo5 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String data = "aaaaa";
		this.getServletContext().setAttribute("data", data);
		
		//请求转给1.jsp,并在JSP中获取数据
		RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/1.jsp");
		rd.forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP '1.jsp' starting page</title>
</head>

<body>

	<font color="red">
		<h1>${data }</h1>
	</font>
</body>
</html>

4,利用ServletContext对象读取资源文件

//读取配置文件
public class ContextDemo6 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		test4();
	}
	
	//使用getRealPath读取资源文件
	private void test4() throws IOException {
		//获取在WEB-INF底下的db.properties的绝对路径
		String path = this.getServletContext().getRealPath("/WEB-INF/db.properties");
		String filename = path.substring(path.lastIndexOf("\\")+1);
		
		FileInputStream in = new FileInputStream(path);
		System.out.println(filename);
		System.out.println(in);
	}
	
	
	//读取不一样位置的资源文件
	private void test3() throws IOException {
		
		//资源文件在cn.yujian.context包下面
		InputStream in  = this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/yujian/context/db.properties");
		System.out.println(in);
		
		//资源文件在WEB-INF目录下
		in  = this.getServletContext().getResourceAsStream("/WEB-INF/db.properties");
		System.out.println(in);
		
	}


	//经过servletContext读取web应用下的资源文件,資源文件在src目录下
	private void test2() throws IOException {
		InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
		Properties prop = new Properties();   //map
		prop.load(in);
		
		String driver = prop.getProperty("driver");
		String url = prop.getProperty("url");
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");
		
		System.out.println(driver);
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


附加:

不是servlet的普通类中如何读取资源文件?

public class Dao {

	//在不是servlet的普通类读取资源文件,(经过类加载的方式读取)
	private static Properties config = new Properties();
	static{
		try{
			//这是直接在src下面的,若是文件在某一个包下面,它前面须要加上包名,如:cn/nihao/db.properties
			InputStream in = Dao.class.getClassLoader().getResourceAsStream("db.properties");//经过类加载器读取资源文件
			config.load(in);
		}catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	
	public String test(){
		String driver = config.getProperty("driver");
		System.out.println(driver);
		return "";
	}
	
	public String get() throws IOException{
		
		//InputStream in = Dao.class.getClassLoader().getResourceAsStream("db.properties");
		//这种方式能够让配置文件改变以后就能生效
		URL url = Dao.class.getClassLoader().getResource("db.properties");
		String path = url.getPath();
		
		FileInputStream in = new FileInputStream(path);
		Properties prop = new Properties();
		prop.load(in);
		
		System.out.println(prop.getProperty("driver"));
		
		return "";
	}
}

这种方式的缺点是,若是资源文件过大会致使内存溢出

相关文章
相关标签/搜索