Showing posts with label ServletConfig. Show all posts
Showing posts with label ServletConfig. Show all posts

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
  • Tuesday, 25 March 2014

    Servlets : ServletConfig

    🚀 Master Java Servlets & Enterprise Architecture!

    Subscribe to Ram N Java for clean Java tutorials, servlet configuration guides, and step-by-step code demonstrations!

    🔔 Subscribe to Ram N Java

    What Is ServletConfig in Java Servlets?

    In Java web applications, servlets often need configuration parameters initialized at startup—such as database connection strings, email configurations, or specific file paths. Hardcoding these values directly into the Java class creates rigid code that requires recompilation whenever a parameter changes. The ServletConfig object acts as a bridge between the servlet container and an individual servlet, providing access to servlet-specific initialization parameters defined in the deployment descriptor (web.xml) or annotations.

    Key Concepts & Object Lifecycle

    • One per Servlet: Unlike ServletContext (which is shared across the entire web application), a unique ServletConfig object is created for each individual servlet in the container.
    • Creation During Initialization: The servlet container instantiates ServletConfig during the servlet initialization phase and passes it to the servlet via the init(ServletConfig config) method.
    • Accessing the ServletContext: The ServletConfig object provides a direct reference to the application-wide ServletContext via getServletContext().

    Essential ServletConfig Methods

    The javax.servlet.ServletConfig interface defines four fundamental methods:

    1. getInitParameter(String name): Returns a String containing the value of the named initialization parameter, or null if it does not exist.
    2. getInitParameterNames(): Returns an Enumeration<String> of all initialization parameter names defined for the servlet.
    3. getServletName(): Returns the name of the servlet instance as defined in the deployment descriptor or @WebServlet annotation.
    4. getServletContext(): Returns the reference to the surrounding ServletContext object.

    Why Use ServletConfig?

    • Configurability Without Recompilation: Change servlet startup values in web.xml without touching compiled Java source code.
    • Encapsulation & Scope Isolation: Keeps configuration parameters scoped exclusively to the servlet that requires them, preventing accidental access or collisions across other servlets.
    • Convenient Access: Because GenericServlet implements ServletConfig, methods like getInitParameter() and getServletContext() can be called directly within any servlet subclass.

    Recommended Next Videos

    Deepen your understanding of servlet initialization and container architecture with these related tutorials from our channel:


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

    Click the below Image to Enlarge
    ServletConfig
    ServletConfig
    ServletConfig

    ServletConfig Project Dir Structure
    ServletConfig

    ServletConfigServlet.java
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Enumeration;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ServletConfigServlet extends HttpServlet
    {
    
      private static final long serialVersionUID = 1L;
    
      ServletConfig             servletConfig           = null;
    
      public void init( ServletConfig servletConfig )
      {
        this.servletConfig = servletConfig;
        System.out.println("\n-----------------------------------------------------");
        System.out.println("init method has been called and servlet is initialized");
        System.out.println("-----------------------------------------------------");
    
        System.out.println("Using 'getInitParameter(String name)' method get the value");
        String driverName = servletConfig.getInitParameter("driverName");
        System.out.println("Driver Name : " + driverName);
    
        System.out.println("\nUsing 'getInitParameterNames()'  method get the value");
        Enumeration<String> paramNames = servletConfig.getInitParameterNames();
    
        while( paramNames.hasMoreElements() )
        {
          String paramName = paramNames.nextElement();
    
          String value = servletConfig.getInitParameter(paramName);
    
          System.out.println("paramName : " + paramName + ", Value: " + value);
    
        }
    
      }
    
      public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException,
                      IOException
      {
    
        System.out.println("\n-----------------------------------------------------");
        System.out.println("doGet method has been called");
        System.out.println("-----------------------------------------------------");
    
        ServletConfig servletConfig = getServletConfig();
        System.out.println("Got servletconfig object using getServletConfig() method : " + servletConfig);
        System.out.println("Servlet Name : " + servletConfig.getServletName());
        System.out.println("ServletContext Object : " + servletConfig.getServletContext());
    
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("<html><body>");
        out.print("<b>hello HTTP servlet</b>");
        out.print("</body></html>");
      }
    
      public void destroy()
      {
        System.out.println("-----------------------------------------------------");
        System.out.println("destroy method has been called and servlet is destroyed");
        System.out.println("-----------------------------------------------------");
      }
    
      public ServletConfig getServletConfig()
      {
        return servletConfig;
      }
    }
    

    web.xml
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    <?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>ServletConfigServlet</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>ServletConfigServlet</servlet-name>
        <servlet-class>ServletConfigServlet</servlet-class>
        
         <init-param>  
          <param-name>driverName</param-name>  
          <param-value>oracle.jdbc.driver.OracleDriver</param-value>  
        </init-param>
        
         <init-param>  
          <param-name>username</param-name>  
          <param-value>ram</param-value>  
        </init-param>
        
        <init-param>  
          <param-name>password</param-name>  
          <param-value>ram</param-value>  
        </init-param>   
        
      </servlet>
      
      <servlet-mapping>
        <servlet-name>ServletConfigServlet</servlet-name>
        <url-pattern>/servletConfig</url-pattern>
      </servlet-mapping>
    </web-app>
    

    index.html
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    <!DOCTYPE HTML><html lang="en"><head>
    <meta charset="UTF-8">
    <title>ServletConfigServlet</title>
    </head>
    <body>
    <p>
    <h3>ServletConfigServlet</H3>
    <p></p>
    <ul>
    
    <li><a href="servletConfig">ServletConfigServlet</a></li>
    
    </ul>
    </body></html>
    

    Environment Used: 

    JDK version :1.6.0_30
    Tomcat version : 7.0.50 

    To Download ServletConfigApp Project Click the below link

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

    See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • Tutorials