Program to demonstrate use of ServletContextListener.
1. Open Link: http://localhost:8080/Excercise/MailContext
The context parameter "adminMail" is made as an attribute and database connection is made when the context is initialized. The listener which checks for context initialization is MailContextListener.
1. Open Link: http://localhost:8080/Excercise/MailContext
The context parameter "adminMail" is made as an attribute and database connection is made when the context is initialized. The listener which checks for context initialization is MailContextListener.
web.xml(To be stored in folder called apache tomcat/webapps/Excercise/WEB-INF in webapps):
<web-app....>
<context-param>
<param-name>adminMail</param-name>
<param-value>java123@oracle.com</param-value>
</context-param>
<listener>
<listener-class>pack1.work.Controller.MailContextListener</listener-class>
</listener>
<servlet>
<servlet-name>ContextL</servlet-name>
<servlet-class>pack1.work.Controller.ContextListenerTester</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextL</servlet-name>
<url-pattern>/MailContext</url-pattern>
</servlet-mapping>
</web-app>
/* This Listener gets the init parameter from DD, passes to Mail class constructor to make a object, set it as an attribute */
MailContextListener (.class to be stored in folder apache tomcat/webapps/Excercise/WEB-INF/classes/pack1/work/Controller )
package pack1.work.Controller;
import javax.servlet.*;
public class MailContextListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent event){
ServletContext context = event.getServletContext();
String mail = (String)context.getInitParameter("adminMail");
Mail mail_id = new Mail(mail);
context.setAttribute("admin", mail_id);
}
public void contextDestroyed(ServletContextEvent event){
/*The attributes get released when context is destroyed, so no memory release functionality to be added*/
}
}
/*Simple method which gets the string through constructor*/
Mail.java (.class to be stored in folder apache tomcat/webapps/Excercise/WEB-INF/classes/pack1/work/Controller )
package pack1.work.Controller;
public class Mail {
public String mail_id;
public Mail(String mail){
mail_id=mail;
}
}
/*Servlet to display the attribute set by Listener when context is initialized.*/
ContextListenerTester(.class to be stored in folder apache tomcat/webapps/Excercise/WEB-INF/classes/pack1/work/Controller )
package pack1.work.Controller;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ContextListenerTester extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)throws IOException, ServletException{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Mail mail = (Mail)getServletContext().getAttribute("admin");
pw.println("The admin id is " + mail.mail_id);
}
}
No comments:
Post a Comment