Signup · Login
Stardeveloper.com  
Home · Tutorials · Forums · Web Hosting Plans · Faisal Khan's Blog · Contact
Search Stardeveloper.com
Stardeveloper RSS Feed
Newsletter
Enter your email address below to be informed every time a new article is posted at Stardeveloper.com:

You can follow Faisal Khan on Twitter
Article Categories
.NET  .NET
  ASP (16)
  ASP.NET (41)
  ADO (16)
  ADO.NET (10)
  COM (6)
  Web Services (4)
  C# (1)
  VB.NET (3)
  IIS (2)

J2EE  J2EE
  JSP (15)
  Servlets (9)
  Web Services (1)
  EJB (4)
  JDBC (4)
  E-Commerce (1)
  J2ME (1)
  Products (1)
  Applets (1)
  Patterns (1)
Log In
UserName Or Email:

Password:

Auto-Login:

Miscellaneous Links
  Submit Article

Hosted by Securewebs.com
 
Home : J2EE : Servlets : Examining Java Servlets in detail. Servlet life cycle, HttpServlet class, ServletConfig and ServletContext Objects
 
  • getServletConfig()Returns a reference to ServletConfig object. More on it later in this article.
  • getServletContext()Returns reference to ServletContext object. More on it later in this article.

You have now seen all of the methods provided to you by the HttpServlet class. You can override all of them except service(), getServletConfig() and getServletContext() methods to provide your own implementation of them. The three methods which stated above should not be overriden as their default implementation is more than enough to suffice.

ServletConfig Class
ServletConfig object is used by the Servlet Container to pass information to the Servlet during it's initialization. Servlet can obtain information regarding initialization parameters and their values using different methods of ServletConfig class. As discussed in ' Your first Java Servlet' article, initialization parameters are name/value pairs used to provide basic information to the Servlet during it's initialization like JDBC driver name, path to database, username, password etc. To learn more about using initialization parameters please see the above article.

Methods of ServletConfig class
Following are the four methods of this class :

  • getInitParameter(String paramName) Returns value of the given parameter. If value of parameter could not be found in web.xml file then a null value is returned.
  • getInitParameterNames() Returns an Enumeration object containing all the names of initialization parameters provided for this Servlet.
  • getServletContext() Returns reference to the ServletContext object for this Servlet. It is similar to getServletContext() method provided by HttpServlet class.
  • getServletName() Returns name of the Servlet as provided in the web.xml file or if none is provided then returns complete class path to the Servlet.

Note that ServletConfig object provides configuration information for the given single Servlet and not for the whole application. If you want to provide some initialization parameters for the whole application than consider using ServletContext object instead.

Example
Since a detailed example with working demo has been discussed in ' Introduction to Servlets, Your first Java Servlet' there is no need to repeat that code here. Please go and see that article. In that article it has been discussed in detail how to give an initialization parameter to a Servlet and then how to access it using getInitParameter() method.

ServletContext class
A ServletContext object represents a complete web application within a Java Virtual Machine. Your web application will typically consist of Servlets, JSP pages, Java beans and other class files. All of these application components run inside a context ( or virtual wrapper ) called ServletContext.

This ServletContext allows all application components to get application level initialization parameters, set and get application attributes, major and minor version of Servlet API this Servlet Container supports, get hold of RequestDispatcher object to forward requests to other application components within the Server or to include response from certain components within the Servlet and to log message to application log file.

To summarize, ServletContext allows application components to interact with each other and to get application level information from the Servlet Container.

Methods of ServletContext Class
Following are the methods of this class :

  • getAttribute(), getAttributeNames(), setAttribute(), removeAttribute() These methods are used to set, get or remove application level objects. For example, one Servlet will set a variable name of type String to a value of "Faisal Khan" :
    public void init(ServletConfig config) throws ServletException {
    	super.init(config);
    	
    	// setting value of name to "Faisal Khan"
    	config.getServletContext().setAttribute("name", "Faisal Khan");
    }
    Then another Servlet can retrieve the value of name by :
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    		throws ServletException, IOException {
    	res.setContentType("text/html");
    	
    	PrintWriter out = res.getWriter();
    	out.print("<html><body>");
    	out.print("<p>My name is : ");
    
    	// retrieving value of name from ServletContext
    	out.print(getServletContext().getAttribute("name").toString());
    
    	out.print("</p></body></html>");
    
    	out.close();
    }
  • getInitParameter(), getInitParameterNames() These methods work much like the getInitParameter(), getInitParameterNames() methods of ServletConfig class except that they return application level initialization parameters. See the example code below.
  • getMinorVersion(), getMajorVersion() Return minor and major version of Servlet API supported by the Servet Container respectively.
  • getMimeType() Returns MIME type of specifed file or null if MIME type is not known.
  • getServerInfo() Returns name and info about the Servlet Container.
  • getResource(), getResourceAsStream() Return URL and InputStream objects for the given path respectively.
  • getNamedDispatcher(), getRequestDispatcher() Return RequestDispatcher object for the given resource path.
  • getRealPath() Returns real path for the given virtual path.
  • getContext() Returns ServletContext object for the given path.
  • log() Writes messages to application log file.

Example using ServletContext Initialization Parameters
Following is the code for declaring an application level initialization parameter which a Servlet later retrieves and displays on the user screen :

Following is the complete code for web.xml file :

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

	<context-param>
		<param-name>website</param-name>
		<param-value>Stardeveloper.com</param-value>
	</context-param>
	
	<servlet>
		<servlet-name>test1</servlet-name>
		<servlet-class>
		com.stardeveloper.servlets.TestServlet1
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
  
</web-app>
  • getServletConfig()Returns a reference to ServletConfig object. More on it later in this article.
  • getServletContext()Returns reference to ServletContext object. More on it later in this article.

You have now seen all of the methods provided to you by the HttpServlet class. You can override all of them except service(), getServletConfig() and getServletContext() methods to provide your own implementation of them. The three methods which stated above should not be overriden as their default implementation is more than enough to suffice.

ServletConfig Class
ServletConfig object is used by the Servlet Container to pass information to the Servlet during it's initialization. Servlet can obtain information regarding initialization parameters and their values using different methods of ServletConfig class. As discussed in ' Your first Java Servlet' article, initialization parameters are name/value pairs used to provide basic information to the Servlet during it's initialization like JDBC driver name, path to database, username, password etc. To learn more about using initialization parameters please see the above article.

Methods of ServletConfig class
Following are the four methods of this class :

  • getInitParameter(String paramName) Returns value of the given parameter. If value of parameter could not be found in web.xml file then a null value is returned.
  • getInitParameterNames() Returns an Enumeration object containing all the names of initialization parameters provided for this Servlet.
  • getServletContext() Returns reference to the ServletContext object for this Servlet. It is similar to getServletContext() method provided by HttpServlet class.
  • getServletName() Returns name of the Servlet as provided in the web.xml file or if none is provided then returns complete class path to the Servlet.

Note that ServletConfig object provides configuration information for the given single Servlet and not for the whole application. If you want to provide some initialization parameters for the whole application than consider using ServletContext object instead.

Example
Since a detailed example with working demo has been discussed in ' Introduction to Servlets, Your first Java Servlet' there is no need to repeat that code here. Please go and see that article. In that article it has been discussed in detail how to give an initialization parameter to a Servlet and then how to access it using getInitParameter() method.

ServletContext class
A ServletContext object represents a complete web application within a Java Virtual Machine. Your web application will typically consist of Servlets, JSP pages, Java beans and other class files. All of these application components run inside a context ( or virtual wrapper ) called ServletContext.

This ServletContext allows all application components to get application level initialization parameters, set and get application attributes, major and minor version of Servlet API this Servlet Container supports, get hold of RequestDispatcher object to forward requests to other application components within the Server or to include response from certain components within the Servlet and to log message to application log file.

To summarize, ServletContext allows application components to interact with each other and to get application level information from the Servlet Container.

Methods of ServletContext Class
Following are the methods of this class :

  • getAttribute(), getAttributeNames(), setAttribute(), removeAttribute() These methods are used to set, get or remove application level objects. For example, one Servlet will set a variable name of type String to a value of "Faisal Khan" :
    public void init(ServletConfig config) throws ServletException {
    	super.init(config);
    	
    	// setting value of name to "Faisal Khan"
    	config.getServletContext().setAttribute("name", "Faisal Khan");
    }
    Then another Servlet can retrieve the value of name by :
    public void doGet(HttpServletRequest req, HttpServletResponse res)
    		throws ServletException, IOException {
    	res.setContentType("text/html");
    	
    	PrintWriter out = res.getWriter();
    	out.print("<html><body>");
    	out.print("<p>My name is : ");
    
    	// retrieving value of name from ServletContext
    	out.print(getServletContext().getAttribute("name").toString());
    
    	out.print("</p></body></html>");
    
    	out.close();
    }
  • getInitParameter(), getInitParameterNames() These methods work much like the getInitParameter(), getInitParameterNames() methods of ServletConfig class except that they return application level initialization parameters. See the example code below.
  • getMinorVersion(), getMajorVersion() Return minor and major version of Servlet API supported by the Servet Container respectively.
  • getMimeType() Returns MIME type of specifed file or null if MIME type is not known.
  • getServerInfo() Returns name and info about the Servlet Container.
  • getResource(), getResourceAsStream() Return URL and InputStream objects for the given path respectively.
  • getNamedDispatcher(), getRequestDispatcher() Return RequestDispatcher object for the given resource path.
  • getRealPath() Returns real path for the given virtual path.
  • getContext() Returns ServletContext object for the given path.
  • log() Writes messages to application log file.

Example using ServletContext Initialization Parameters
Following is the code for declaring an application level initialization parameter which a Servlet later retrieves and displays on the user screen :

Following is the complete code for web.xml file :

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

	<context-param>
		<param-name>website</param-name>
		<param-value>Stardeveloper.com</param-value>
	</context-param>
	
	<servlet>
		<servlet-name>test1</servlet-name>
		<servlet-class>
		com.stardeveloper.servlets.TestServlet1
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
  
</web-app>

Previous ( 1 Gone )( 1 Remaining ) Next

See all comments and questions (post-ad) posted for this tutorial.


Comments/Questions ( Threads: 4, Comments: 4 )
    Contains 1 or more replies by the Author of this Article.
    Contains 1 or more replies by Faisal Khan.

  1. Retrieve image from MySQL database!
  2. How many times init() will get called in case of instance pool
  3. Report error
  4. calling servlet method from another servlet

Post Comments/Questions

In order to post questions/comments, you must be logged-in. If you are not a member yet, then signup, otherwise login. Once you login then come back to this page and you'll see a form right here which will allow you to post comments/questions.

Please note, one of the benefits of signing up is to be notified immediately by email everytime you receive a reply to the thread you have subscribed to.

 
© 1999 - 2009 Stardeveloper.com, All Rights Reserved.