ServletConfig和ServletContext对象的作用和使用

ServletConfig


官方定义:
public abstract interface ServletConfig
A servlet configuration object used by a servlet container used to pass information to a servlet during initialization.


一个servlet的配置对象,用来给servlet容器传递信息到servlet,在Servlet初始化的时候。


ServletConfig的几个方法:
1.getInitParameter(java.lang.String name) ------>根据name,获取初始化信息
 Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist.


2.getInitParameterNames() ------>获取所有初始化信息的名称
          Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.


3.getServletContext() ------>获取ServletContext对象 
          Returns a reference to the ServletContext in which the caller is executing.


4.getServletName() ------>获取这个servlet实例的名称
          Returns the name of this servlet instance.

例子:

在web.xml中配置servlet并且设置servlet的初始化信息;

[java]  view plain  copy
  1. <servlet>  
  2.         <servlet-name>Servlet_03</servlet-name>  
  3.         <servlet-class>com.enterise.always.servlet.Servlet_03</servlet-class>  
  4.         <init-param>  
  5.             <param-name>name_01</param-name>  
  6.             <param-value>value_01</param-value>  
  7.         </init-param>  
  8.         <init-param>  
  9.             <param-name>name_02</param-name>  
  10.             <param-value>value_02</param-value>  
  11.         </init-param>  
  12.     </servlet>  
  13.     <servlet-mapping>  
  14.         <servlet-name>Servlet_03</servlet-name>  
  15.         <url-pattern>/servlet/Servlet_03</url-pattern>  
  16.     </servlet-mapping>  

java:

[java]  view plain  copy
  1. package com.enterise.always.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Enumeration;  
  5.   
  6. import javax.servlet.ServletConfig;  
  7. import javax.servlet.ServletContext;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. public class Servlet_03 extends HttpServlet {  
  14.     private static final long serialVersionUID = 1L;  
  15.   
  16.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
  17.             throws ServletException, IOException {  
  18.           
  19.         doPost(req, resp);  
  20.     }  
  21.   
  22.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
  23.             throws ServletException, IOException {  
  24.         //1.获取ServletConfig对象  
  25.         ServletConfig config = getServletConfig();  
  26.           
  27.             //1.getInitParameter  
  28.             String para_01 = config.getInitParameter("name_01");  
  29.             String para_02 = config.getInitParameter("name_02");  
  30.               
  31.             System.out.println("para_01----------->"+para_01);  
  32.             System.out.println("para_02----------->"+para_02);  
  33.               
  34.             //2.getInitParameterNames  
  35.             Enumeration enumeration = config.getInitParameterNames();  
  36.             while(enumeration.hasMoreElements()){  
  37.                 String name = (String) enumeration.nextElement();  
  38.                 String value = config.getInitParameter(name);  
  39.                 System.out.println("name----------->"+name);  
  40.                 System.out.println("value----------->"+value);  
  41.             }  
  42.             //3.getServletContext  
  43.             ServletContext servletContext = config.getServletContext();  
  44.             System.out.println("servletContext----------->"+servletContext);  
  45.             //4.getServletName  
  46.             String servletName = config.getServletName();  
  47.             System.out.println("servletName----------->"+servletName);  
  48.     }  
  49. }  

后台打印数据:

[java]  view plain  copy
  1. para_01----------->value_01  
  2. para_02----------->value_02  
  3. name----------->name_02  
  4. value----------->value_02  
  5. name----------->name_01  
  6. value----------->value_01  
  7. servletContext----------->org.apache.catalina.core.ApplicationContextFacade@b398da  
  8. ----------->Servlet_03  

例子:

在servlet创建的时候,获取数据库的链接信息:

1.在web.xml中配置数据库的连接信息

[java]  view plain  copy
  1. <servlet>  
  2.         <servlet-name>Servlet_04</servlet-name>  
  3.         <servlet-class>com.enterise.always.servlet.Servlet_04</servlet-class>  
  4.         <init-param>  
  5.             <param-name>driver</param-name>  
  6.             <param-value>com.mysql.jdbc.driver</param-value>  
  7.         </init-param>  
  8.         <init-param>  
  9.             <param-name>url</param-name>  
  10.             <param-value>jdbc:mysql://localhost:3306/data</param-value>  
  11.         </init-param>  
  12.         <init-param>  
  13.             <param-name>user</param-name>  
  14.             <param-value>root</param-value>  
  15.         </init-param>  
  16.         <init-param>  
  17.             <param-name>password</param-name>  
  18.             <param-value>root</param-value>  
  19.         </init-param>  
  20.         <load-on-startup>2</load-on-startup>  
  21.     </servlet>  

2.在servlet中获取数据:
[java]  view plain  copy
  1. public void init(ServletConfig config) throws ServletException {  
  2.         System.out.println("Servlet_04.init()--2");  
  3.           
  4.         Enumeration enumeration = config.getInitParameterNames();  
  5.         while(enumeration.hasMoreElements()){  
  6.             String name = (String) enumeration.nextElement();  
  7.             String value = config.getInitParameter(name);  
  8.               
  9.             System.out.println("name----------->"+name);  
  10.             System.out.println("value-----------     >"+value);  
  11.         }  
  12.     }  
后台打印数据:

[java]  view plain  copy
  1. 2013-8-31 15:59:36 org.apache.catalina.core.ApplicationContext log  
  2. 信息: SessionListener: contextInitialized()  
  3. Servlet_04.init()--2  
  4. name----------->driver  
  5. value-----------     >com.mysql.jdbc.driver  
  6. name----------->password  
  7. value-----------     >root  
  8. name----------->user  
  9. value-----------     >root  
  10. name----------->url  
  11. value-----------     >jdbc:mysql://localhost:3306/data  
  12. 2013-8-31 15:59:36 org.apache.coyote.http11.Http11Protocol start  
  13. 信息: Starting Coyote HTTP/1.1 on http-8080  
  14. 2013-8-31 15:59:36 org.apache.jk.common.ChannelSocket init  
  15. 信息: JK: ajp13 listening on /0.0.0.0:8009  
  16. 2013-8-31 15:59:36 org.apache.jk.server.JkMain start  
  17. 信息: Jk running ID=0 time=0/22  config=null  
  18. 2013-8-31 15:59:36 org.apache.catalina.startup.Catalina start  
  19. 信息: Server startup in 738 ms  

从数据打印信息中来看,在servlet创建的时候,就会调用初始化的方法。

原因是在web.xml中配置了:

<load-on-startup>2</load-on-startup>

用途:

如果在<servlet>元素中配置了一个<load-on-startup>元素,那么WEB应用程序在启动时,就会装载并创建Servlet的实例对象、以及调用Servlet实例对象的init()方法。

为web应用写一个InitServlet,这个servlet配置为启动时装载,为整个web应用创建必要的数据库表和数据。

如果没有在servlet配置这个参数的话,在装载并创建servlet对象的时候是不会调用init方法的。


----------------------------------------------------------------------------------------------------------------------------------------------------

ServletContext:


官方文档定义:
public abstract interface ServletContext
Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. 


There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.) 


In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead. 


The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. 


安装在一个服务器中的一个特定URL名字空间(比如,/myapplication)下的所有Servlet,JSP,JavaBean等Web部件的集合构成了一个Web的应用,每一个Web应用(同一JVM),容器都会有一个背景对象,而javax.servlet.ServletContext接口就提供了访问这个背景对象的途径。


也就是说在整个web应用中,只有一个ServletContext,WEB容器在启动时,它会为每个WEB应用程序都创建一个对应的ServletContext对象,它代表当前web应用。


1.获取ServletContext实例:

	//1.第一种方式
		ServletContext servletContext_01 = this.getServletContext();
	//2.第二种方式
		ServletContext servletContext_02 = this.getServletConfig().getServletContext();
2.利用ServletContext实现数据共享:
	在Servlet_03中:
	//往servletContext对象中设置数据
	ServletContext servletContext = config.getServletContext();
	servletContext.setAttribute("name", "共享数据---》");
	在Servlet_04中:
	//从servletContext对象中获取数据
	ServletContext servletContext = getServletConfig().getServletContext();
	System.out.println("value------------>"+servletContext.getAttribute("name"));

3.在web.xml中配置初始化信息。
	<!-- context的配置信息 -->
	<context-param>
		<param-name>name_param1</param-name>
		<param-value>value_param1</param-value>
	</context-param>
	<context-param>
		<param-name>name_param2</param-name>
		<param-value>value_param2</param-value>
	</context-param>




	获取初始化参数
		ServletContext context = this.getServletContext();
		
		Enumeration enumeration = context.getInitParameterNames();
		while(enumeration.hasMoreElements()){
			String name = (String) enumeration.nextElement();
			String value = (String) context.getInitParameter(name);
			
			System.out.println("name-------------->"+name);
			System.out.println("value----------------->"+value.toString());
		}
	


	控制台打印数据:


	name-------------->name_param2
	value----------------->value_param2
	name-------------->name_param1
	value----------------->value_param1


4.实现servlet的转发


		//4.实现servlet的转发。
		ServletContext context = this.getServletContext();
		//在request设置参数,然后在jsp界面中获取。
		req.setAttribute("name", "value");
		
		RequestDispatcher requestDispatcher = context.getRequestDispatcher("/index.jsp");
		requestDispatcher.forward(req,resp);


		在jsp界面获取的数据:
		 <%
    			String value = (String)request.getAttribute("name");
    			System.out.println("value-------------->"+value);
    		 %>
5.读取资源的配置文件。
		ServletContext context = this.getServletContext();
		
		InputStream inputStream = context.getResourceAsStream("/db.properties");
		
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] by = new byte[1024];
		int len = 0;
		
		while((len = inputStream.read(by))!= -1){
			outStream.write(by, 0, len);
		}
		
		String content = new String(outStream.toByteArray());
		System.out.println("content------------->"+content);
		
		outStream.close();
		inputStream.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值