Newsletter

Example of ServletContext in Java

Servlets » on Feb 2, 2013 { 14 Comments } By Sivateja

ServletContext is one of pre-defined interface available in javax.servlet.*; Object of ServletContext interface is available one per web application. An object of ServletContext is automatically created by the container when the web application is deployed.

Assume there exist a web application with 2 servlet classes, and they need to get some technical values from web.xml, in this case ServletContext concept will works great, i mean all servlets in the current web application can access these context values from the web.xml but its not the case in ServletConfig, there only particular servelet can access the values from the web.xml which were written under <servlet> tag, hope you remember.  Have doubt ? just check Example of ServletConfig

How to Get ServletContext Object into Our Servlet Class

In servlet programming we have 3 approaches for obtaining an object of ServletContext interface

Way 1

ServletConfig conf = getServletConfig();
ServletContext context = conf.getServletContext();

  • First obtain an object of ServletConfig interface
  • ServletConfig interface contain direct method to get Context object, getServletContext();

Way 2

Direct approach, just call getServletContext() method available in GenericServlet [pre-defined].  In general we are extending our class with HttpServlet, but we know HttpServlet is the sub class of GenericServlet.

public class Java4s extends HttpServlet
{
public void doGet/doPost(-,-)
{
//….
}
ServletContext ctx = getServletContext();
}

Way 3

We can get the object of ServletContext by making use of HttpServletRequest object, we have direct method in HttpServletRequest interface.

public class Java4s extends HttpServlet
{
public void doGet/doPost(HttpServletRequest req,-)
{
ServletContext ctx = req.getServletContext();
}
}

How to Retrieve Data from ServletConfig Interface Object

ServletContext provide these 2 methods, In order to retrieve the data from the web..xml [ In web.xml we have write <context-param>tag to provide the values, and this <context-param> should write outside of <servlet> tag as context should be accessed by all servlet classes ].

In general database related properties will be written in this type of situation, where every servlet should access the same data.

  • public String getInitParameter(“param name”);
  • public Enumeration getInitParameterNames();

I am not going to explain about these methods, these are similar to ‘Retrieve Client Input Data in Servlet‘ but here we are retrieving values from web.xml that’s it.

Example of ServletContext

Directory Structure

Files Required

  • index.html
  • OnServletContext.java
  • web.xml

index.html

<font face="verdana" size="2px">
    <form action="onContext" method="post">
       Example on ServletContext<br> 
       <input type="submit" value="Click Here">
    </form>
</font>

OnServletContext.java

package java4s;

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 OnServletContext extends HttpServlet  
{
    protected void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
    {
        PrintWriter pw=res.getWriter();
        res.setContentType("text/html");

        // I am using 2nd way to create Context object
        ServletContext context=getServletContext();  

        String s1=context.getInitParameter("n1");
        String s2=context.getInitParameter("n2");

        pw.println("n1 value is " +s1+ " and n2 is " +s2);

       pw.close();    
    }
}

web.xml

<web-app>

    <context-param>
        <param-name> n1 </param-name>
        <param-value> 100 </param-value>
    </context-param>

    <context-param>
        <param-name> n2  </param-name>
        <param-value> 200 </param-value>
    </context-param>

    <servlet>
        <servlet-name>onServletContext</servlet-name>
        <servlet-class>java4s.OnServletContext</servlet-class>
    </servlet>

    <servlet-mapping>
            <servlet-name>onServletContext</servlet-name>
            <url-pattern>/onContext</url-pattern>
    </servlet-mapping>

   <welcome-file-list>  
        <welcome-file>index.html</welcome-file>  
   </welcome-file-list> 

</web-app>

Output

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

14 Responses to “Example of ServletContext in Java”
  1. i have a doubt for this way of creating object-
    ServletConfig conf = getServletConfig();
    ServletContext context = conf.getServletContext();

    in which situations do we need to use object of servletconfig to create objcet of servletContext?

  2. siva says:

    i have a doubt for this way of creating object-
    ServletConfig conf = getServletConfig();
    ServletContext context = conf.getServletContext();

    in which situations do we need to use object of servletconfig to create objcet of servletContext?

  3. vishal says:

    i want a connection with oracle using ServletContext and in this program i create a connection and this connection i want to declared globally and access to whole servlet program

  4. dheeraj says:

    this is very helpful thanx for sharing…

  5. Pallavi HN says:

    Sir I have one doubt,
    We have three ways to create an object for ServletContext .In which situation we have to use which way to create an object.Please explain me sir.

  6. pritha says:

    explanation with example is very easy to understand concept .thankx sir

  7. java guy says:

    This will not work. ServletContext ctx = req.getServletContext();
    You need to access it from the session.

    req.getSession().getServletContext();

  8. Jitendra says:

    I am not getting what exactly going on here.

  9. Lavakumar says:

    it helped me lot and lot bro

  10. vasu says:

    your examples are understand easily…………..

  11. A stephen Raj says:

    Wow….. Supreb site..

    Here you’ve posted lots of helpful code for beginners that i know of.
    It’s very helpful to every one including expr people also..
    you express your thoughts as short and sweet.

    Thanks,
    Steve

  12. Arun says:

    could you please provide the content of sessions concept in servlet on java4s site.

  13. Soumya says:

    Please explain how the advantage of ServletContext(using web.xml i.e., without compiling and restarting the services) can be achieved in servlet 3.0

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.