Example of ServletContextListener:

We will combine one employe class with the servletcontext object.

Fils needed:
-one servletcontextlistener class (MyServletContextListener.java)
-one pojo class (Emp.java)
-one HttpServlet class(hello.java)
-one dd file as usual (web.xml)
-one html file (index.html)
Here we will set the Emp attribute to the servletcontext and that object will be shared among all the servlets and jsps in webapp. This is not an issue which servlet will be initialized first.

Emp.java:
public class Emp{
private String name="bhabani";
private String city="blore";
Emp(String name,String city){this.name=name;this.city=city;}
public String getname(){return name;}
public String getcity(){return city;}}

MyServletContextListener.java
import javax.servlet.*;
public class MyServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
ServletContext context=event.getServletContext();//ask the event for the servlet context
Emp emp1=new Emp("bhabani","blore");
Emp emp2=new Emp("pinku","bbsr");
context.setAttribute("emp1",emp1);
context.setAttribute("emp2",emp2);}


public void contextDestroyed(ServletContextEvent sce) {
//no clean up code required}}
The class must implement ServletContextListener class.
Here two Emp references(emp1,emp2) are created and associated with the ServletContext.
Hello.java
import java.io.*;
import javax.servlet.*;
public class hello extends HttpServlet{
public void doGet(HttpServletRequest hsreq,HttpServletResponse hsrep)throws ServletException,IOException{
hsrep.setContentType("text/html");
PrintWriter out=hsrep.getWriter();
out.println("<center><h1><font color='red'>Hello Client..,</font></h1></center>");
Emp emp1=(Emp)getServletContext().getAttribute("emp1");
Emp emp2=(Emp)getServletContext().getAttribute("emp2");
out.println(emp1.getname()+" stays in "+emp1.getcity()+"<br>");
out.println(emp2.getname()+" stays in "+emp2.getcity());}}
Here we get the Emp attribute from servlet context as usual.

Web.xml

<web-app>
<listener>
<description>ServletContextListener</description>
<listener-class>MyServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello.do</url-pattern>
</servlet-mapping>
</web-app>

No comments:

Post a Comment