Showing posts with label ServletContext. Show all posts
Showing posts with label ServletContext. Show all posts

Friday, 6 June 2014

Servlets : ServletContext Attribute Demo

🚀 Master Java Servlets & Enterprise Web Development!

Subscribe to Ram N Java for clean Java tutorials, servlet architecture deep dives, and practical coding walkthroughs!

🔔 Subscribe to Ram N Java

Understanding Application Scope in Java Servlets

In Java EE web applications, sharing data globally across multiple servlets, JSPs, and user sessions is a frequent architectural requirement. While request scope is short-lived and session scope belongs to a single client, application scope spans the entire lifetime of the web application. By leveraging ServletContext attributes, developers can store and access shared resources and global states across all web components seamlessly.

Core ServletContext Attribute Methods

The ServletContext interface provides essential methods to manage application-scoped attributes:

  • setAttribute(String name, Object object): Binds an object to a given attribute name in the application context. If an attribute with the same name exists, it is overwritten.
  • getAttribute(String name): Retrieves the stored attribute value as an Object, which can be typecast back to its target class type. Returns null if no attribute exists with that name.
  • removeAttribute(String name): Removes the attribute associated with the specified name from the application scope.
  • getAttributeNames(): Returns an Enumeration<String> containing all attribute names currently stored in the servlet context.

Step-by-Step Implementation Flow

  1. Obtain the ServletContext: Access the application context within your servlet by calling getServletContext() (inherited from GenericServlet) or via request.getServletContext().
  2. Set the Global Attribute: Store your shared object or application state using servletContext.setAttribute("appName", "RamNJavaApp").
  3. Access from Another Servlet: In any other servlet or JSP within the application, fetch the context and call servletContext.getAttribute("appName") to read the shared object.
  4. Remove the Attribute: When cleaning up resources or resetting state, call servletContext.removeAttribute("appName").

Why Use ServletContext Attributes?

  • Global Data Sharing: Provides a centralized repository accessible by all servlets, filters, and JSPs in the web module.
  • Application-Wide Lifespan: Stored attributes persist for the complete lifetime of the application container until undeployed or stopped.
  • Resource Efficiency: Ideal for sharing expensive singleton resources, global configuration settings, or cross-cutting metadata.

Recommended Next Videos

Continue mastering Java Servlet scopes and architecture with these related tutorials from our channel:


Click here to watch in Youtube : https://www.youtube.com/watch?v=xoL0FBK2H6A

Click the below Image to Enlarge
Servlets : ServletContext Attribute Demo
ServletContextAttributeDemo Project Dir Structure
Servlets : ServletContext Attribute Demo

FirstServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("----------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("-------------------------------------------");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        ServletContext servletContext = getServletContext();

        servletContext.setAttribute("CompanyName", "Wipro");
        servletContext.setAttribute("Location", "India");

        out.print("<a href='servlet2'> visit</a>");

        out.close();

    }

    public void destroy()
    {
        System.out.println("----------------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("--------------------------------------------");
    }

}

SecondServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SecondServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    public void init() throws ServletException
    {
        System.out.println("--------------------------------------------");
        System.out.println(" Init method is called in "
                + this.getClass().getName());
        System.out.println("---------------------------------------------");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        ServletContext servletContext = getServletContext();

        String CompanyName = (String) servletContext.getAttribute("CompanyName");
        out.print("CompanyName :  " + CompanyName + "<br>");

        out.print("*************************************************************"
                + "<br>");

        Enumeration<String> namesEnum = servletContext.getAttributeNames();
        while (namesEnum.hasMoreElements())
        {
            String name = (String) namesEnum.nextElement();
            out.print(name + ":");
            Object value = servletContext.getAttribute(name);
            out.print(value);
            out.print("<br>");
        }

        out.close();
    }

    public void destroy()
    {
        System.out.println("--------------------------------------------");
        System.out.println(" destroy method is called in "
                + this.getClass().getName());
        System.out.println("--------------------------------------------");
    }

}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    metadata-complete="true" version="3.0">
    <display-name>ServletContextAttributeDemo</display-name>
    <description>
        This is a simple web application with a source code organization
        based on the recommendations of the Application Developer's Guide.
    </description>
    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>FirstServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>s1</servlet-name>
        <url-pattern>/servlet1</url-pattern>
    </servlet-mapping>
    <servlet>
        <servlet-name>s2</servlet-name>
        <servlet-class>SecondServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>s2</servlet-name>
        <url-pattern>/servlet2</url-pattern>
    </servlet-mapping>
</web-app>

index.html
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ServletContextAttributeDemo</title>
</head>
<body>
    <form action="servlet1" method="GET">
                    
        <input type="submit" value="Call FirstServlet" />
        
    </form>
</body>
</html>


Environment Used 

JDK version :1.7.0_51
Tomcat version : 7.0.50 

To Download ServletContextAttributeDemo Project Click the below link

https://sites.google.com/site/javaee4321/servlets/ServletContextAttributeDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Friday, 2 May 2014

    Servlets : ServletContext [context-param]

    Master Core Java & Servlets!

    Subscribe to Ram N Java for beginner-friendly coding walkthroughs, web architecture lessons, and hands-on Java guides!

    🔔 Subscribe to Ram N Java

    Understanding Context Parameters in web.xml

    In a Java web application, you often need global configuration settings that should be accessible by all servlets, JSPs, and filters—such as database URLs, administrator emails, or shared system settings. Instead of hardcoding these values or restricting them to a single servlet, Java Servlets allow you to define them as application-wide context parameters inside web.xml using the <context-param> element.

    These values are loaded by the servlet container when the application starts up and are exposed globally via the ServletContext object.

    Configuring & Reading Context Parameters

    To read context parameters in your servlet code, obtain the ServletContext instance (via getServletContext()) and use the following built-in methods:

    • getInitParameter(String name): Returns the String value of the specified context initialization parameter, or null if it does not exist.
    • getInitParameterNames(): Returns an Enumeration<String> containing the names of all context parameters defined in the application.
    <!-- web.xml snippet -->
    <context-param>
        <param-name>adminEmail</param-name>
        <param-value>admin@ramnjava.com</param-value>
    </context-param>

    // Inside your Servlet class
    ServletContext context = getServletContext();
    String adminEmail = context.getInitParameter("adminEmail");
    System.out.println("Admin Email: " + adminEmail);

    Key Advantages of Using ServletContext for Configuration

    • Application-Wide Availability: Unlike servlet-specific init parameters, context parameters are shared across every component in the web application.
    • Centralized Maintenance: Modify environment configurations in web.xml without altering or recompiling Java source code.
    • One Context per Web App: Each deployed web application maintains a single ServletContext instance, ensuring clean isolation and consistency.

    Recommended Related Tutorials

    Continue exploring servlet fundamentals and configuration with these tutorials from Ram N Java:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=u0YYCV9IxK4

    Click the below Image to Enlarge

    ServletContextInitParam Project Dir Structure

    SevletContextDemoServlet.java
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class SevletContextDemoServlet extends HttpServlet
    {
    
        private static final long serialVersionUID = 1L;
    
        public void init() throws ServletException
        {
            System.out
                    .println("------------------------------------------------------");
            System.out.println(" Init method is called in "
                    + this.getClass().getName());
            System.out
                    .println("------------------------------------------------------");
        }
    
        // Method to handle GET method request.
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
        {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
    
            ServletContext context = getServletContext();
    
            out.print("<b>Read specfic initParam using context.getInitParameter"
                    + "(String paramName )</b> <br><br>");
    
            String driverName = context.getInitParameter("drivername");
            out.print(driverName + "<br><br>");
    
            out.print("<b>Read All InitParameters using "
                    + "getInitParameterNames() method</b> <br>");
    
            Enumeration<String> initParamNamesEnum = context
                    .getInitParameterNames();
            String paramName = "";
            while (initParamNamesEnum.hasMoreElements())
            {
                paramName = initParamNamesEnum.nextElement();
                String paramValue = context.getInitParameter(paramName);
                out.print("<br> " + paramName + " : " + paramValue);
            }
        }
    
        // Method to handle POST method request.
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException
        {
            doGet(request, response);
        }
    
        public void destroy()
        {
            System.out
                    .println("------------------------------------------------------");
            System.out.println(" destroy method is called in "
                    + this.getClass().getName());
            System.out
                    .println("------------------------------------------------------");
        }
    }
    

    web.xml
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        metadata-complete="true" version="3.0">
        <display-name>ServletContextInitParam</display-name>
        <description>
            This is a simple web application with a source code organization
            based on the recommendations of the Application Developer's Guide.
        </description>
    
        <context-param>
            <param-name>drivername</param-name>
            <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
        </context-param>
    
        <context-param>
            <param-name>username</param-name>
            <param-value>system</param-value>
        </context-param>
    
        <context-param>
            <param-name>password</param-name>
            <param-value>oracle</param-value>
        </context-param>
        
        <servlet>
            <servlet-name>context</servlet-name>
            <servlet-class>SevletContextDemoServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>context</servlet-name>
            <url-pattern>/context</url-pattern>
        </servlet-mapping>
    </web-app>
    

    index.html
    <!DOCTYPE HTML>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Context Test</title>
    </head>
    <body>
        <li><a href="context">Context Test</a></li>
    </body>
    </html>
    
    

    Environment Used

    JDK version :1.6.0_30
    Tomcat version : 7.0.50 

    To Download ServletContextInitParamApp Project Click the below link

    https://sites.google.com/site/javaee4321/servlets/ServletContextInitParamApp.zip?attredirects=0&d=1

     See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Thursday, 1 May 2014

    Servlets : ServletContext vs ServletConfig

    Master Core Java & Servlets!

    Subscribe to Ram N Java for beginner-friendly coding walkthroughs, web architecture lessons, and hands-on Java guides!

    🔔 Subscribe to Ram N Java

    Understanding ServletConfig vs. ServletContext

    When building Java web applications, configuring parameters and sharing information across components are fundamental tasks. Two of the most commonly confused interfaces in the javax.servlet package are ServletConfig and ServletContext.

    While both interfaces are used to supply initialization values and communicate with the container, their scope and lifecycle differ significantly. Knowing when to use ServletConfig versus ServletContext is crucial for architecting clean, maintainable web applications.

    Key Differences at a Glance

    • Scope: ServletConfig is servlet-specific (one per servlet), meaning its parameters are private to that single servlet. In contrast, ServletContext has an application-wide scope (one per web application) shared across all servlets, filters, and JSPs.
    • Configuration in web.xml: Parameters for ServletConfig are defined inside a specific <servlet> block using <init-param>. Parameters for ServletContext are defined globally using <context-param> outside of servlet declarations.
    • Creation: The servlet container creates a ServletConfig object when instantiating that specific servlet. A ServletContext object is created once when the entire web application is deployed.
    // Accessing ServletConfig (Servlet-specific)
    ServletConfig config = getServletConfig();
    String specificParam = config.getInitParameter("myParam");

    // Accessing ServletContext (Application-wide)
    ServletContext context = getServletContext();
    String globalParam = context.getInitParameter("adminEmail");

    Summary of Best Practices

    • Use ServletConfig: For settings unique to a single servlet, such as a specialized file path, a default view page, or a private configuration key.
    • Use ServletContext: For application-wide data and resources, including database URLs, global cache references, administrator contact details, and cross-servlet attributes.
    • Access Context via Config: ServletConfig provides a convenient reference to the global context via config.getServletContext().

    Recommended Related Tutorials

    Continue exploring servlet fundamentals and configuration with these tutorials from Ram N Java:


    Click here to watch in Youtube :  https://www.youtube.com/watch?v=4S8YfXbkXRU

    Click the below Image to Enlarge
    ServletContext vs ServletConfig
    ServletContext vs ServletConfig
    ServletContext vs ServletConfig
    ServletContext vs ServletConfig
    ServletContext vs ServletConfig
    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Servlets : ServletContext Introduction

    Master Core Java & Servlets!

    Subscribe to Ram N Java for beginner-friendly coding walkthroughs, web architecture lessons, and hands-on Java guides!

    🔔 Subscribe to Ram N Java

    What is ServletContext?

    In Java web applications, the ServletContext interface (from the javax.servlet package) represents the entire web application environment within the servlet container. When a web application is deployed, the servlet container creates exactly one ServletContext object for that entire application.

    This single context instance acts as a central communication bridge between your servlets, filters, and the servlet container, enabling global resource sharing and application-wide configuration management.

    Core Capabilities of ServletContext

    The ServletContext interface provides essential methods that enable developers to:

    • Access Global Parameters: Read application-wide initialization parameters configured in web.xml using getInitParameter(String name).
    • Share Application-Scoped Attributes: Store and retrieve shared objects across all users and servlets using setAttribute(), getAttribute(), and removeAttribute().
    • Access Web Resources: Load static files, real filesystem paths, and input streams using getRealPath() or getResourceAsStream().
    • Container Information & Logging: Retrieve container version details via getServerInfo() and log operational messages directly to the server log via log().
    // Obtaining the ServletContext instance inside a Servlet
    ServletContext context = getServletContext();

    // Reading an application-wide init parameter
    String adminEmail = context.getInitParameter("adminEmail");

    // Storing and retrieving global application-scoped data
    context.setAttribute("appTheme", "dark");
    String theme = (String) context.getAttribute("appTheme");

    Key Characteristics of ServletContext

    • One Context per Application: Every deployed web application has its own isolated ServletContext instance shared by all of its servlets and JSPs.
    • Application Lifecycle Scope: The context remains active from the moment the web application is loaded until it is undeployed or the server shuts down.
    • Global State Management: Serves as the ultimate shared storage mechanism when data needs to persist beyond individual requests or user sessions.

    Recommended Related Tutorials

    Continue exploring servlet fundamentals and configuration with these tutorials from Ram N Java:


    Click here to watch in Youtube : https://www.youtube.com/watch?v=08ImN21Ct0Y

    Click the below Image to Enlarge
    ServletContext Introduction
    ServletContext Introduction
    ServletContext Introduction
    ServletContext Introduction

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Older Posts Home

    Tutorials