ServletContext接口功能

一.    获取web应用的初始化参数 

使用getInitParameterNames()getInitParameter(String name)来获得web应用中的初始化参数

 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter outPrintWriter = response.getWriter();
		ServletContext context = this.getServletContext();                  //定义一个ServletContext对象
		Enumeration enumeration = context.getInitParameterNames();  //用集合得方式存储配置文件中所有的name
		while(enumeration.hasMoreElements()){                              //判断是否为空
			String nameString = enumeration.nextElement();                 //跨过头部  提取第一个name
			String passString = context.getInitParameter(nameString);    //用getInitParameter(name)提取value
			outPrintWriter.print(nameString+"  "+passString);            //输出
		}
		
	}

 

二.  实现多个servlet的数据共享

  1. setAttribute(String name,String value) 来设置共享的数据 
  2. getAttribute(String name) 来获得共享得数据值
  3. removeAttribute(String name) 删除
  4. getAttributeNames()

ServletSet类

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		ServletContext context = this.getServletContext();
		context.setAttribute("强月城", "123456");
	}

ServletGet类

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		ServletContext context = this.getServletContext();
		String pasString = (String) context.getAttribute("强月城");   //要强制类型转换  getAttribute的返回值为object
		out.print(pasString);
	}

 

三.  获取web应用下的资源文件(配置文件或图片)

  1.  InputStream getResourceAsInputstream(String path)
  2. String getRealPath(String path)
  3. URL getResource(String path)

 实例

 1.在src路径下创建配置文件创建文件source.properties      (项目被发布后资源文件的路径发生改变)

 2.获取资源文件   定义的InoutStream and  load()方法   getProperty()方法

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		ServletContext context = this.getServletContext();
		InputStream in = context.getResourceAsStream("D:/Myeclipse/新建文件夹/demo/WebRoot/WEB-INF/classes/source.properties");
		Properties pros = new Properties();   //定义内容对象
		pros.load(in);     加载InputStream对象
		out.print(pros.getProperty("name"));  //使用getProperty函数输出文件里的哈希值对
		out.print(pros.getProperty("password"));
	}

 

你可能感兴趣的:(web)