Servlet Tutorial

Servlet Context scope

Servlet Context scope:

An object of ServletContext is used for having a common data for a group of servlets which belongs to same web application. The data of ServletContext object can be accessed through out all the methods of the servlet of a particular web.xml

Methods:

The following methods are used to add local data of a servlet to ServletContext object, removing the existing data of ServletContext object.

public void setAttribute (String, Object); - 1
public Object getAttribute (String); - 2
public void removeAttribute (String); - 3 
public Enumeration getAttributeNames (); - 4

Load-on-startup:

Load-on-startup is basically used for giving equal response for all the clients who are accessing a particular web application. By default after making request the ServletContext object will be created by servlet container. Because of this first response takes more amount of time and further responses will take minimum amount of time. Therefore to avoid the discrepancy in response time we use a concept of load-on-startup. <load-on-startup> tag will be used as a part of <servlet> tag since it is specific to the servlet.

load on startup

If the priority value is positive for a group of servlets then whose objects will be created based on ascending order of the priorities. If the priority value is zero then that servlet object will be created at the end. If the priority value of a servlet is negative then that servlet object will not be created i.e., neglected.

When we use load-on-startup as a part of web.xml the container will create an object of a servlet before first request is made.

web.xml:

<web-app>
    <servlet>
        <servlet-name>abc</servlet-name>
        <servlet-class>DdServ</servlet-class>
        <load-on-startup>10</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>abc</servlet-name>
        <url-pattern>/ddurl</url-pattern>
    </servlet-mapping>
</web-app>

DdServ.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class DdServ extends HttpServlet {

    public DdServ() {
        System.out.println("SERVLET OBJECT IS CREATED");
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        System.out.println("I AM FROM doGet ()");
        pw.println("<h3>I AM FROM doGet ()</h3>");
    }
};