ServletConfig and Servlet Context in Servlet


ServletContext

             ServletContext is used to read the configration information defined in context param in web container file(web.xml), These context information can be read by any servlets in that application

  

ServletConfig

             A servlet configuration object used by a servlet container to pass information to a servlet during initialization using init param. Only the specific servlet can access it.

 

Example

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
	id="WebApp_ID" version="2.5">

	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>
	
	<context-param>
	    <param-name>site</param-name>
	    <param-value>candidjava.com</param-value>
	</context-param>
	
	<servlet>
		<servlet-name>LoginController</servlet-name>
		<servlet-class>com.candidjava.LoginController</servlet-class>
		<init-param>
			<param-name>email</param-name>
			<param-value>info@candidjava.com</param-value>
		</init-param>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>LoginController</servlet-name>
		<url-pattern>/LoginController</url-pattern>
	</servlet-mapping>
</web-app>

Servlet program

package com.candidjava;

import java.io.IOException;

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

/**
 * Servlet implementation class LoginController
 */
public class LoginController extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	ServletConfig sc=getServletConfig();
	String e=sc.getInitParameter("email");
		
	ServletContext scx= getServletContext();
	String site=scx.getInitParameter("site");
	
	
	System.out.println(e);
	System.out.println(site);

	response.sendRedirect("page.html");
	}

}

Output

info@candidjava.com

candidjava.com


Screenshot

            

                        


Download

Servlet context config example war

Servlet context config example zip



Related Post

Comments

Chetan
         Thanks for this information...

©candidjava.com