Write a servlet which illustrate the concept of ServletContext?



web.xml:

<web-app>
<context-param>
<param-name>v1</param-name>
<param-value>10</param-value>
</context-param>
<context-param>
<param-name>v2</param-name>
<param-value>20</param-value>
</context-param>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>Serv1</servlet-class>
<init-param>
<param-name>v3</param-name>
<param-value>30</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>Serv2</servlet-class>
<init-param>
<param-name>v4</param-name>
<param-value>40</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/firstserv</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/secondserv</url-pattern>
</servlet-mapping>
</web-app>

Serv1.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Serv1 extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  ServletConfig config = getServletConfig();
  ServletContext ctx = config.getServletContext();
  String val1 = ctx.getInitParameter("v1");
  String val2 = ctx.getInitParameter("v2");
  String val3 = config.getInitParameter("v3");
  String val4 = config.getInitParameter("v4");
  int sum = Integer.parseInt(val1) + Integer.parseInt(val2);
  pw.println("<h3> Value of v1 is " + val1 + "</h3>");
  pw.println("<h3> Value of v2 is " + val2 + "</h3>");
  pw.println("<h3> Value of v3 is " + val3 + "</h3>");
  pw.println("<h3> Value of v4 is " + val4 + "</h3>");
  pw.println("<h2> Sum = " + sum + "</h2>");
 }
}


Serv2.java:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class Serv2 extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  res.setContentType("text/html");
  PrintWriter pw = res.getWriter();
  ServletContext ctx = getServletContext();
  Enumeration en = ctx.getInitParameterNames();
  while (en.hasMoreElements()) {
   Object obj = en.nextElement();
   String cpname = (String) obj;
   String cpvalue = ctx.getInitParameter(cpname);
   pw.println("</h2>" + cpvalue + " is the value of " + cpname + "</h2>");
  }
 }
}




No comments:

Post a Comment