Sunday, December 16, 2012

ServletContext Interface

Object of ServletContext Interface is used get parameter value corresponding to parameter name and in a web Application there is only one ServletContext object.
using parameter name we can share corresponding value to more than one servlet by invoking parameter name in that servlet using ServletContext object.

It is better to change data values at one place rather than changing in all servlets.
 <?xml version="1.0" encoding="UTF-8"?>  
 <web-app version="2.5" xmlns="" xmlns:xsi="" xsi:schemaLocation="">  
we can create object of ServletContext by two ways which are shown below.
 import javax.servlet.ServletException;  
 import javax.servlet.http.HttpServlet;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import java.sql.*;  
 import javax.servlet.ServletContext;  
 public class ServletContextDemo extends HttpServlet {   
   protected void doGet(HttpServletRequest req, HttpServletResponse res)  
   throws ServletException, IOException {  
     //Method 1 to get object of ServletContext  
     ServletContext context1=getServletContext();  
     //Method 2 to get object of ServletContext  
     ServletContext context2=getServletConfig().getServletContext();  
     String dd1=context1.getInitParameter("d1");  
     String dd2=context2.getInitParameter("d2");  
       Connection connection=DriverManager.getConnection(dd2,"hr","hr");  
     catch(Exception e){ }  

Setting and getting Attribute using ServletContext Object
public void setAttribute(String name,Object object);

Binds an object to a given attribute name in this ServletContext. If the name specified is already used for an attribute, this method will replace the attribute with the new to the new attribute.
getServletContext().setAttribute("myString", s1);

public Object getAttribute(String name);

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.


No comments:

Popular Posts