SevletContextExample Program In Java

In this tutorial we learn how to use ServletContext interface in Servlet based applications and how to run that servlet in Tomcat which is integrated with eclipse.

How to retrieve context information in Servlet class?

In Servlet class first we need to create ServletContext reference by calling the getServletContext() and then we need to retrieve the context information for this servlet which is configured in webxml. Remember context information is available for all the resources like servlets and jsp components in the application.

 

1. Create a dynamic project in eclipse.

        Create a dynamic web project in eclipse(click “new” ->Dynamic web project) and add below servlet class to project, If you dont know how to create dynamic web project please see my previouse example Helloworld Servlet Example Program with video tutorial.

2. Write the Servlet class, ServletContextExample.java

 

 3. configure the servlet in deployment descriptor i.e in web.xml

 

 4. deploy and run the servlet in server.

Right click on the project and click on “Run As” -> “Run on Server”.

OUTPUT :

 

servletcontextexample

 

Download  Source Code

 

Posted in servlets and tagged , .

Leave a Reply

Your email address will not be published. Required fields are marked *