AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



java-servlet: Event and Listener in Servlet?

Event classes

The event classes are as follows:

1)ServletRequestEvent
2)ServletContextEvent
3)ServletRequestAttributeEvent
4)ServletContextAttributeEvent
5)HttpSessionEvent
6)HttpSessionBindingEvent

Event interfaces

The event interfaces are as follows:

1)ServletRequestListener
2)ServletRequestAttributeListener
3)ServletContextListener
4)ServletContextAttributeListener
5)HttpSessionListener
6)HttpSessionAttributeListener
7)HttpSessionBindingListener
8)HttpSessionActivationListener

Could you plz explain Event & Lisener Concept with above mention Classes and interfaces.

For each class & interface I need a example.







Thanking you.

java x 210
servlet x 19
Posted On : 2016-08-13 10:29:42.0
profile MOHAMMAD SALEEM BASHA - anyforum.in MOHAMMAD SALEEM BASHA
266150
up-rate
4
down-rate

Answers


Events are basically occurrence of something. Changing the state of an object is known as an event. We can perform some important tasks at the occurrence of these exceptions, such as counting total and current logged-in users, creating tables of the database at time of deploying the project, creating database connection object etc.

There are many Event classes and Listener interfaces in the javax.servlet and javax.servlet.http packages. We´ll see some examples.


ServletContextEvent and ServletContextListener:
-----------------------------------------------------------------------------------------------------
The ServletContextEvent is notified when web application is deployed on the server. If you want to perform some action at the time of deploying the web application such as creating database connection, creating all the tables of the project etc, you need to implement ServletContextListener interface and provide the implementation of its methods.

Constructor of ServletContextEvent class:
---------------------------------------------------------------------------------------------------
There is only one constructor defined in the ServletContextEvent class. The web container creates the instance of ServletContextEvent after the ServletContext instance.

ServletContextEvent(ServletContext e)

Method of ServletContextEvent class:
-----------------------------------------------------------------------------------------
There is only one method defined in the ServletContextEvent class:

public ServletContext getServletContext(): returns the instance of ServletContext.
Methods of ServletContextListener interface

There are two methods declared in the ServletContextListener interface which must be implemented by the servlet programmer to perform some action such as creating database connection etc.

1) public void contextInitialized(ServletContextEvent e): is invoked when application is deployed on the server.
2) public void contextDestroyed(ServletContextEvent e): is invoked when application is undeployed from the server.

In this example, we are retrieving the data from the emp32 table. To serve this, we have created the connection object in the listener class and used the connection object in the servlet.

index.html:
-----------------------------------------
<a href="servlet1">fetch records</a>
MyListener.java
import javax.servlet.*;
import java.sql.*;

public class MyListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent event) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//storing connection object as an attribute in ServletContext
ServletContext ctx=event.getServletContext();
ctx.setAttribute("mycon", con);

}catch(Exception e){e.printStackTrace();}
}

public void contextDestroyed(ServletContextEvent arg0) {}
}


MyListener.java:
----------------------------------------------
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class FetchData extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

try{
//Retrieving connection object from ServletContext object
ServletContext ctx=getServletContext();
Connection con=(Connection)ctx.getAttribute("mycon");

//retieving data from emp32 table
PreparedStatement ps=con.prepareStatement("select * from emp32",
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

ResultSet rs=ps.executeQuery();
while(rs.next()){
out.print("<br>"+rs.getString(1)+" "+rs.getString(2));
}

con.close();
}catch(Exception e){e.printStackTrace();}

out.close();
}
}


Example of ServletContextListener to create table of a project:
------------------------------------------------------------------------------------------------------------------
In this example, we are creating table of the project. So we don´t need to create all the tables manually in the database.

MyListener.java:
------------------------------------------------
import javax.servlet.*;
import java.sql.*;

public class MyListener implements ServletContextListener{

public void contextInitialized(ServletContextEvent arg0) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

String query="create table emp32(id number(10),name varchar2(40))";
PreparedStatement ps=con.prepareStatement(query);
ps.executeUpdate();

System.out.println(query);

}catch(Exception e){e.printStackTrace();}
}

public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("project undeployed");

}
}


HttpSessionEvent and HttpSessionListener:
-------------------------------------------------------------------------------------
The HttpSessionEvent is notified when session object is changed. The corresponding Listener interface for this event is HttpSessionListener.

We can perform some operations at this event such as counting total and current logged-in users, maintaing a log of user details such as login time, logout time etc.

Methods of HttpSessionListener interface:
----------------------------------------------------------------------------------
There are two methods declared in the HttpSessionListener interface which must be implemented by the servlet programmer to perform some action.

1.) public void sessionCreated(HttpSessionEvent e): is invoked when session object is created.
2.) public void sessionDestroyed(ServletContextEvent e): is invoked when session is invalidated.

In this example, are counting the total and current logged-in users. For this purpose, we have created three files:
1.) index.html: to get input from the user.
2.) MyListener.java: A listener class that counts total and current logged-in users and stores this information in ServletContext object as an attribute.
3.) First.java: A Servlet class that creates session and prints the total and current logged-in users.
4.) Logout.java: A Servlet class that invalidates session.

index.html:
---------------------------
<form action="servlet1">
Name:<input type="text" name="username"><br>
Password:<input type="password" name="userpass"><br>

<input type="submit" value="login"/>
</form>


MyListener.java:
-------------------------------------------------
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class CountUserListener implements HttpSessionListener{
ServletContext ctx=null;
static int total=0,current=0;

public void sessionCreated(HttpSessionEvent e) {
total++;
current++;

ctx=e.getSession().getServletContext();
ctx.setAttribute("totalusers", total);
ctx.setAttribute("currentusers", current);

}

public void sessionDestroyed(HttpSessionEvent e) {
current--;
ctx.setAttribute("currentusers",current);
}

}

First.java:
---------------------------------
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class First extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("username");
out.print("Welcome "+n);

HttpSession session=request.getSession();
session.setAttribute("uname",n);

//retrieving data from ServletContext object
ServletContext ctx=getServletContext();
int t=(Integer)ctx.getAttribute("totalusers");
int c=(Integer)ctx.getAttribute("currentusers");
out.print("<br>total users= "+t);
out.print("<br>current users= "+c);

out.print("<br><a href=´logout´>logout</a>");

out.close();
}

}


Logout.java:
--------------------------------------
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session=request.getSession(false);
session.invalidate();//invalidating session

out.print("You are successfully logged out");


out.close();
}

}

Posted On : 2016-08-13 23:22:34
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523185319357
Reply This Thread
up-rate
3
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in