📜  Servlet – 上下文事件和上下文监听器

📅  最后修改于: 2022-05-13 01:55:10.652000             🧑  作者: Mango

Servlet – 上下文事件和上下文监听器

ServletContextEvent类为 Web 应用程序的 servlet 上下文的更改提供警报/通知。 ServletContextListener是一个类,它接收有关 servlet 上下文更改的警报/通知并对其进行操作。当上下文被初始化和删除时,ServletContextListener 用于执行关键任务。简而言之,ServletContextEvent 和 ServletContextListener函数串联;每当 ServletContext 发生变化时,ServletContextEvent 都会广播一个通知,由 ServletContextListener 接收,然后根据该消息执行各种职责。

ServletContextEvent 类的构造函数

ServletContextEvent(ServletContext e)

在 ServletContextEvent 类中,只有一个构造函数。在 ServletContext 实例化之后,Web 容器会生成一个 ServletContextEvent 实例。

ServletContextEvent 的方法

public ServletContext getServletContext()

ServletContextListener 接口的方法

Method

Action Performed 

void contextInitialized(ServletContextEvent e)When the application is first initialized, this method is called.
void contextDestroyed(ServletContextEvent e)When the application is destroyed, this method is called.

示例: ServletContextEvent 和 ServletContextListener

在此示例中,我们将必须创建一个名为 counter 的表,其中包含一个名为 pageview 的列来保存页面浏览量。通过使用这个数据库记录,我们将找出页面浏览的总数。

A.文件:index.html

HTML


XML

 

MyListenerGfg

 

CounterGfg
CounterGfg

 

CounterGfg
/CounterGfg

 


Java
// Java Program to Illustrate MyListener Class
 
// Importing required classes
import java.sql.*;
import javax.servlet.*;
 
// Class
public class MyListenerGfg implements ServletContextListener {
    // Class data members
    ServletContext ctx;
    Connection con;
    Statement s;
    PreparedStatement ps;
    ResultSet rs;
    int count;
 
    // Method 1
    public void contextInitialized(ServletContextEvent sce) {
 
        // Try block to check for exceptions
        try {
 
            // Loading drivers using forName() method
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/geeksforgeeks", "root", "root");
 
            s = con.createStatement();
 
            // Fetching pageviews value from table counter
            rs = s.executeQuery("select pageview from counter");
 
            // Iterating using next() method
            while (rs.next()) {
                count = rs.getInt(1);
            }
 
            ctx = sce.getServletContext();
            ctx.setAttribute("pcount", count);
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Display exception with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
 
    // Method 2
    public void contextDestroyed(ServletContextEvent sce) {
 
        try {
 
            ctx = sce.getServletContext();
            count = (Integer)ctx.getAttribute("pcount");
            ps = con.prepareStatement("update counter set pcount='" + count + "'");
            ps.executeUpdate();
        }
        catch (Exception e) {
             
            e.printStackTrace();
        }
    }
}


Java
// Java Program to Illustrate Counter Class
 
// Importing required classes
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Class
// Extending HttpServlet class
public class CounterGfg extends HttpServlet {
    // Method
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
 
        PrintWriter out = response.getWriter();
        ServletContext ctx = getServletContext();
 
        Integer count = (Integer)ctx.getAttribute("pcount");
 
        out.println(count + ": pageview");
        ctx.setAttribute("pcount", ++count);
    }
}


B.文件:web.xml

XML


 

MyListenerGfg

 

CounterGfg
CounterGfg

 

CounterGfg
/CounterGfg

 

C.文件:MyListenerGfg。Java

Java

// Java Program to Illustrate MyListener Class
 
// Importing required classes
import java.sql.*;
import javax.servlet.*;
 
// Class
public class MyListenerGfg implements ServletContextListener {
    // Class data members
    ServletContext ctx;
    Connection con;
    Statement s;
    PreparedStatement ps;
    ResultSet rs;
    int count;
 
    // Method 1
    public void contextInitialized(ServletContextEvent sce) {
 
        // Try block to check for exceptions
        try {
 
            // Loading drivers using forName() method
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/geeksforgeeks", "root", "root");
 
            s = con.createStatement();
 
            // Fetching pageviews value from table counter
            rs = s.executeQuery("select pageview from counter");
 
            // Iterating using next() method
            while (rs.next()) {
                count = rs.getInt(1);
            }
 
            ctx = sce.getServletContext();
            ctx.setAttribute("pcount", count);
        }
 
        // Catch block to handle exceptions
        catch (Exception e) {
 
            // Display exception with line number
            // using printStackTrace() method
            e.printStackTrace();
        }
    }
 
    // Method 2
    public void contextDestroyed(ServletContextEvent sce) {
 
        try {
 
            ctx = sce.getServletContext();
            count = (Integer)ctx.getAttribute("pcount");
            ps = con.prepareStatement("update counter set pcount='" + count + "'");
            ps.executeUpdate();
        }
        catch (Exception e) {
             
            e.printStackTrace();
        }
    }
}

D.文件:CounterGfg。Java

Java

// Java Program to Illustrate Counter Class
 
// Importing required classes
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
 
// Class
// Extending HttpServlet class
public class CounterGfg extends HttpServlet {
    // Method
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        response.setContentType("text/html;charset=UTF-8");
 
        PrintWriter out = response.getWriter();
        ServletContext ctx = getServletContext();
 
        Integer count = (Integer)ctx.getAttribute("pcount");
 
        out.println(count + ": pageview");
        ctx.setAttribute("pcount", ++count);
    }
}

输出:

单击该链接后,将加载以下页面,该页面显示页面查看次数表示用户访问该页面的次数。每次刷新或重新访问页面时,页面计数都会增加。