Back to: Java Servlets Tutorials
Servlet Scopes in Java
In this article, I am going to discuss Servlet Scopes in Java Web Application. As part of this article, we are going to discuss the following pointers in detail which are related to Servlet Scopes in Java.
- How many Servlet instances created in a java web application?
- What is the lifetime of a servlet instance?
- How many ServletConfig objects?
- What is the lifetime of the ServletConfig object?
- How many request objects?
- What is the lifetime of the request object?
- What are the different Servlet Scopes?
- Request Scope of a Servlet
- Who calls doGet(-,-) and doPost(-,-) ?
- How are doGet() and doPost() methods implemented in Httpservlet?
- What are the methods of ServletConfig object?
- How many interfaces does GenericServlet implement?
- How many init() methods are implemented in GenericServlet?
- Explain about ServletContext
- Explain about the ServletContext scope or application scope
- Explain about the ServletConfig object
How many Servlet instances created in a java web application?
1 per application.
What is the lifetime of a servlet instance?
Application lifetime
How many ServletConfig objects?
1 per servlet
What is the lifetime of the ServletConfig object?
That of the servlet.
How many request objects?
One per client request.
What is the lifetime of the request object?
One request-response cycle.
What are the different Servlet Scopes?
There are 3 scopes in servlet.
- Request scope
- Session scope
- Application scope/ ServletContext scope
Explain the Request Scope of a Servlet.
If a data item is store in request object it is said to be in request scope. The Request object has 4 methods to deal with request scoped data.
- setAttribute (String name, object value)
- object getAttribute(String name)
- removeAttribute (String name)
- Enumeration getAttributeNames()
The setAttribute() method is used to store (and update) a data item in the request object. For example
request.setAttribute(“one”, 10);
request.setAttribute(“two”, 20);
The getAttribute() method is used to retrieve the data item from the request scope.
The removeAttribute() method is used to delete the data item from the request scope.
The getAttributeNames() method returns an Enumerations of strings. Each string represents one attribute name. This method is used to retrieve all data items from the scope at a time (one by one).
Note: getAttribute() and getParameter() methods returns null if with that name no data item exists in request object.
The Request object is shared among those servlets which participate in request dispatching within one request-response cycle.
Note: Scope concept comes into play if and only if data sharing among the servlets of the application is required.
Who calls doGet(-,-) and doPost(-,-) ?
Servlet Engine cannot call these two methods as they are not life cycle methods specified in the servlet interface. The HttpServlet class has two service(-,-) methods
- public service(ServletRequest request, ServletResponse response)
- protected service(HttpServletRequest request, HttpServletResponse response)
The Servlet Container calls the public service method which is the life cycle method of the Servlet interface. The Public service method is implemented in Httpservlet so as to call the protected service() method. The protected service method is implemented in HttpServlet to find out the upcoming request type and based on that type it calls doGet() or doPost() method once.
Note: For each client request, servlet container immediately calls doGet() or doPost() method once.
How are doGet() and doPost() methods implemented in Httpservlet?
The doGet() method is implemented to display the following error response
“HTTP method GET is not supported by this URL”
The doPost() method is implemented to display the following error response
“HTTP method POST is not supported by this URL”
What are the methods of ServletConfig object?
There are four methods in the ServletConfig interface
- String getInitParameter(String): This method takes init-param name as an argument and returns its param value.
- String getServletName(): This method returns the registration name of the Servlet
- ServletContext getServletContext(): This method returns ServletContext object reference
- Enumeration getParameterNames(): This method returns an Enumeration of String. Each String represents one init param name
For example:
public void init (ServletConfig config) { String rname = config.getServletName (); System.out.println ("registration name of the servlet is: " + rname); ServletContext sc = config.getServletContext (); System.out.println (sc); java.util.Enumeration e = config.getInitParameterNmaes (); while (e.hasMoreElements ()) { String pname = (String) e.nextElement (); String pvalue = config.getInitParameter (pname); System.out.println (pname + " : " + pvalue); } }
How many interfaces does GenericServlet implement?
GenericServlet implements 3 interfaces
- java.io.Serializable
- javax.servlet.ServletConfig (has 4 methods)
- javax.servlet.Servlet (5 methods)
GenericServlet implements the Servlet interface so that the classes down the hierarchy are eligible to act as a servlet. The GenericServlet implements ServletConfig so that all the methods of ServletConfig can be called in a user-defined servlet without the need of servlet config reference. The GenericServlet implements a Serializable interface so that if required user-defined servlet instance can be stored into the file system of the web server machine or can be exported to another machine in the network.
How many init() methods are implemented in GenericServlet?
Two init() methods are implemented(body provided) in GenericServlet class.
- init()
- init(ServletConfig)
The zero-argument init method and parameterized init method. The init(ServletConfig config) is the life cycle method of the servlet program and the init() method is not the life cycle method and it is convenience method given to the programmer to place the initialization logic of the servlet program.
GenericServlet.java
public abstract class GenericServlet implements Servlet, ServletConfig, Serializable { private ServletConfig config; public void init () { // empty method } // not life cycle method public void init (ServletConfig config) { this.config = config; init (); } //life cycle method public ServletConfig getServletConfig () { return config; } public String getInitParameter (String pname) { String value = config.getInitParameter (pname); return value; } // other methods }
Note: In predefined HttpServletClass there are no init() methods. If at all the init method is required to be implemented in a user-defined servlet go for the zero-argument init method. If the parameterized init method is implemented chance of calling the ServletConfig method in the doGet() or doPost() method without ServletConfig reference.
What is the output from the following piece of code?
public class MyServlet extends HttpServlet { public void init (ServletConfig config) { } Public void doGet (HttpServletRequest request, HttpServletResponse response) { System.out.println (getInitParameter ("p1")); } }
Output: java.lang.NullPointerException details are displayed. To overcome NullPointerException ensure that GenericServlet provided parameterized init() method is executed.
Explain about ServletContext.
ServletContext is a library interface of Servlet API. The Servlet container implements javax.servlet.ServletContext interface. As soon as the application is deployed and before receiving any client request servlet container creates a ServletContext object.
ServletContext object is one per application. During initialization phase of every servlet, container encapsulates ServletContext reference into ServletConfig object. By calling getServletContext() method on ServletConfig object ServletContext reference is acquired in a servlet.
ServletContext sc= config.getServletContext();
ServletContext sc = getServletContext();
ServletContext acts as an information repository to store application-level data. It is one per web application. So, it is called a global memory of web applications.
ServletContext object means it is the object of a java class (Container supplied) implementing javax.servlet.ServletContext interface. Servlet Container creates this object either during deployment of the web application or during server startup.
Servlet container destroys this object automatically when the web application is undeployed or reloaded or stopped or when the server is stopped or restarted. The data kept in the ServletContext object is visible and accessible in all servlet, JSP programs of the web application.
Explain about the ServletContext scope or application scope.
A data item stored in ServletContext object is said to be in application scope. The SevletContext object is destroyed only when the application is undeployed. ServletContext interface has 4 attribute methods to deal with application scope data. SevletContext object is majorly used for two purposes
- For context parameters
- For application scoped data
All the web components of the web application shared the data if it is stored in ServletContext object. Name, value pair of textual information supplied to the application at the time of application deployment is nothing but context parameter. Context parameterss are supplied through web.xml as follows
<context-param>
<param-name>p3</param-name>
<param-value>scott</param-value>
</context-param>
<context-param>
<param-name>p4</param-name>
<param-value>tiger</param-value>
</context-param>
At the time of application deployment servlet container encapsulates context parameter into servlet context object. There context parameters are available to all the web component of the web application. In a servlet context parameters are accquired by calling getParameter() on servletcontext object For example
ServletContext sc = getServletContext();
String user = sc.getInitParameter(“p3”);
String pwd = sc.getInitParameter(“p4”);
Whenever some init() parameter are required for multiple servlets of the application better go for context parameter as init() parameter are not shared among the servlets, ServletContext object can create a RequestDispatcher object also to facilitate inter-servlet communication. For example
ServletContext sc= getServletContext();
RequestDispatcher rd = sc.getNamedDispatcher(“other servlet registration name”);
Rd.forward(request, response);
Develop a WEB application where you need to enter the account number and gets the details of that account number from the database.
Input.html
<html> <body bgcolor ="cyan"> <center> <h1>Employee Deatils</h1> <form action ="./dburl" method="get"> Employee id: <input type="text" name ="teno"> <br><br> <input type="submit" value="getDetails"> </form> </center> </body> </html>
Web.xml:
<web-app> <servlet> <servlet-name>one</servlet-name> <servlet-class>DBServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>one</servlet-name> <url-pattern>/dburl</url-pattern> </servlet-mapping> <context-param> <param-name>driver</param-name> <param-value>oracle.jdbc.driver.OracleDriver</param-value> </context-param> <context-param> <param-name>cs</param-name> <param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value> </context-param> <context-param> <param-name>username</param-name> <param-value>system</param-value> </context-param> <context-param> <param-name>pwd</param-name> <param-value>pranaya</param-value> </context-param> <welcome-file-list> <welcome-file>input.html</welcome-file> </welcome-file-list> </web-app>
DBServlet.java
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class DBServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { try{ //read context parameter value ServletContext sc = getServletContext(); String driver = sc.getInitParameter("driver"); String cs = sc.getInitParameter("cs"); String un = sc.getInitParameter("username"); String pwd = sc.getInitParameter("pwd"); // create the jdbc connection object Class.forName(driver); Connection con = DriverManager.getConnection(cs, un, pwd); PreparedStatement ps = con.prepareStatement("select accno, name, balance from account where accno = ?"); // read form data int accno = Integer.parseInt(request.getParameter("teno")); //write business logic ps.setInt(1, accno); //execute the query ResultSet rs =ps.executeQuery(); PrintWriter out = response.getWriter(); response.setContentType("text/html"); // process the result set out.println("<html>"); out.println("<body bgcolor = cyan>"); if(rs.next()) { out.println("name=" + rs.getString(2)); out.println("account number=" + rs.getInt(1)); out.println("balance=" + rs.getFloat(3)); } else out.println("with that account number no account exist"); out.println("</body>"); out.println("</html>"); out.close(); rs.close(); ps.close(); con.close(); } catch(Exception e) { e.printStackTrace(); } } }
Explain about the ServletConfig object.
- It is one per servlet program or JSP program.
- ServletConfig object means it is the object of servlet container supplied java class implementing javax.ServletConfig interface.
- This object is useful to pass additional data to the servlet and to read additional details from the servlet.
- This object is useful to read servlet init parameter values from web.xml files of the web application.
- Servlet container creates the servlet config object in the instantiation and initialization process of our servlet class object.
- Servlet container destroys our servlet class object in the destruction process of our servlet object.
In the next article, I am going to discuss Session Tracking in Servlets. Here, in this article, I try to explain Servlet Scopes in Java Web Application. I hope this article will help you to understand Servlet Scopes in Java.