June 18, 2011

Context or Application attributes on the ServletContext object

Context attributes, also called Application attribute (since context attributes are said to have applicaiton scope) are set on the ServletContext object of the Servlet API.

1) Create a Servlet class, ServletOne.java in the src folder of the web application. This Servlet contains code to set an attribute in the Application scope.

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class ServletOne extends HttpServlet {
 
   public void doGet (HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   
      ServletContext sc = getServletContext();
      sc.setAttribute("testAttribute", "testValue");
   
      PrintWriter out = res.getWriter();
   
      out.println("<html><body>");
      out.println("Context Attribute Set. <br/>");
      out.print("<a href=\"two\">");
      out.println("Click to access ServletTwo</a>");
      out.println("</body></html>");
   }
}


2) Create a second Servlet Class, ServletTwo.java also in the src folder of the web application. This servlet procures the attribute set in the Application scope and prints its value.

package info.icontraining.servlets;

import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;

public class ServletTwo extends HttpServlet {
 
   public void doGet (HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException {
   
      ServletContext sc = getServletContext();
      String value = (String) sc.getAttribute("testAttribute");
   
      PrintWriter out = res.getWriter();
   
      out.println("Context Attribute procured");
      out.println("Value is = " + value);
   }
}


3) Configure both servlets in the web.xml file present within the WebContent/WEB-INF folder of the web application

<servlet>
   <servlet-name>servletOne</servlet-name>
   <servlet-class>info.icontraining.servlets.ServletOne</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>servletOne</servlet-name>
   <url-pattern>/one</url-pattern>
</servlet-mapping>
  
<servlet>
   <servlet-name>servletTwo</servlet-name>
   <servlet-class>info.icontraining.servlets.ServletTwo</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>servletTwo</servlet-name>
   <url-pattern>/two</url-pattern>
</servlet-mapping>


4) Test the code by typing the following URL in the browser

http://localhost:8080/WebAppName/one

No comments:

Post a Comment