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 2 3 4 5 6 7 8 |
ServletContext context=getServletContext(); String site=context.getInitParameter("website"); here "paramname" which configured in web.xml |
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
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 |
package com.connect2java.servletcontext; 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 ServletContextExample extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ServletContext context=getServletContext(); String site=context.getInitParameter("website"); out.println("<h1>Hi Welcome to " + site + " , This is Servlet context Example.</h1>"); out.println("</body>"); } } |
3. configure the servlet in deployment descriptor i.e in 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 |
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>ServletContextExample</display-name> <servlet> <servlet-name>ServletConfigExample</servlet-name> <servlet-class>com.connect2java.servletcontext.ServletContextExample</servlet-class> </servlet> <context-param> <param-name>website</param-name> <param-value>www.connect2java.com</param-value> </context-param> <servlet-mapping> <servlet-name>ServletConfigExample</servlet-name> <url-pattern>/context</url-pattern> </servlet-mapping> </web-app> |
4. deploy and run the servlet in server.
Right click on the project and click on “Run As” -> “Run on Server”.
OUTPUT :
Download Source Code