一、概念
servlet监听器的主要目的是给web应用增加事件处理机制,以便更好的监视和控制web应用的状态变化,从而在后台调用相应处理程序。
二、监听器的类型
1.根据监听对象的类型和范围,分为3类
Request事件监听器
HttpSession事件监听器
ServletContext事件监听器
2.八个监听接口和六个监听事件
三、ServletContext监听
1.Application对象
application是ServletContext的实例,由JSP容器默认创建。Servlet中调用getServletContext()方法得到ServletContext的实例。
全局对象即Application范围的对象,初始化阶段的变量值在web.xml中,经由<context-param>元素所设定的变量,它的范围也是Application的范围
2.ServletContextListener接口
用于监听Web应用启动和销毁的事件,监听器类需要实现ServletContextListener接口。
该接口的主要方法;
void contextInitialized(ServletContextEvent se):通知正在接受的对象,应用程序已经被加载及初始化
void contextDestroyed(ServletContextEvent se):通知正在接受的对象,应用程序已经被销毁
ServletContextEvent的主要方法:ServletContext getServletContext():取得当前的ServletContext对象
3.ServletContextAttributeListener
用于监听Web应用属性改变的事件,包括增加、删除、修改属性。监听器类需要实现ServletContextAttributeListener接口
ServletContextAttributeListener接口的主要方法:
void attributeAdded(ServletContextAttributeEvent se):若有对象加入Application的范围,通知正在收听的对象。
void attributeRemoved(ServletContextAttributeEvent se):若有对象从Application范围移除,通知正在收听的对象。
void attributeReplaced(ServletContextAttributeEvent se):若在Application的范围中,有对象取代另一个对象时,通知正在收听的对象
ServletContextAttributeEvent中的主要方法:
getName():返回属性名称
getValue()返回属性的值
四、HttpSession 会话监听
1.HttpSessionListener
主要方法:
sessionCreated(HttpSessionEvent se):session创建
sessionDestroyed(HttpSessionEvent se):session销毁
2.HttpSessionActivationListener:
监听器监听Http会话的情况
3.HttpSessionAttributeListener:
监听HttpSession中属性的操作
该接口的主要方法:
void attributeAdded(HttpSessionBindingEvent se):监听Http会话中的属性添加
void attributeRemoved(HttpSessionBindingEvent se):监听Http会话中的属性移除
void attributeReplaced(HttpSessionBindingEvent se):监听Http会话中的属性更改操作
4.HttpSessionBindingListener
监听Http会话中对象的绑定信息
getSession():获取session对象
getName():返回session增加、删除、或替换的属性名称
getValue():返回session增加、删除、或替换的属性值
五、ServletRequest监听
可以监听客户端的请求
1.ServletRequestListener接口
用于监听客户端的请求初始化和销毁事件,需要实现ServletRequestListener接口
接口中的方法:
requestInitialized(ServletRequestEvent):通知当前对象请求已经被加载及初始化
requestDestroyed(ServletRequestEvent):通知当前对象,请求已经被消除
ServletRequestEvent实例中的方法
getServletRequest():获取ServletRequest对象
getServletContext():获取ServletContext对象
2.ServletRequestAttributeListener
用于监听Web应用属性改变的事件,包括增加属性、删除属性、修改属性
接口方法:
void attributeAdded(ServletRequestAttributeEvent e):向Request对象添加新属性
void attributeRemoved(ServletRequestAttributeEvent e):从request对象中删除属性
void attributeReplaced(ServletRequestAttributeEvent e):替换对象中现有属性值
ServletRequestAttributeEvent中的主要方法:
getName():返回Request增加、删除、或替换的属性名称
getValue():返回Request增加、删除、或替换的属性的值
六、存储在线用户信息的例子
1.login.jsp页面实现用户登录
- <body>
- <form method="get" action="logindo">
- <center>
- <h2>用户登录</h2>
- <hr />
- <br /> 用户名: <input type="text" name="userName" /> <br />
- <input type="submit" value="登录" />
- </center>
- </form>
- </body>
2.建立存储用户信息的类:UserList.java
- package listener;
-
- import java.util.Vector;
-
- public class UserList {
- private static Vector online = new Vector();
-
- public static void addUser(String userName){
- online.addElement(userName);
- }
-
- public static void removeUser(String userName){
- online.removeElement(userName);
- }
-
- public static int getUserCount(){
- return online.size();
- }
- public static Vector getVector(){
- return online;
- }
- }
****Vector 类提供了实现可增长数组的功能,随着更多元素加入其中,数组变的更大。在删除一些元素之后,数组变小。 Vector 有三个构造函数,
public Vector(int initialCapacity,int capacityIncrement)
public Vector(int initialCapacity)
public Vector()
Vector 运行时创建一个初始的存储容量initialCapacity,存储容量是以capacityIncrement 变量定义的增量增长。初始的存储容量和capacityIncrement 可以在Vector 的构造函数中定义。第二个构造函数只创建初始存储容量。第三个构造函数既不指定初始的存储容量也不指定capacityIncrement。
Vector 类提供的访问方法支持类似数组运算和与Vector 大小相关的运算。类似数组的运算允许向量中增加,删除和插入元素。
****
3.写监听器类
- package listener;
-
- import javax.servlet.http.HttpSessionAttributeListener;
- import javax.servlet.http.HttpSessionBindingEvent;
- import javax.servlet.http.HttpSessionEvent;
- import javax.servlet.http.HttpSessionListener;
-
- public class OnlineListener implements HttpSessionListener,HttpSessionAttributeListener{
-
- public void attributeAdded(HttpSessionBindingEvent se) {
-
- UserList.addUser(String.valueOf(se.getValue()));
- System.out.println("session("+se.getSession().getId()+")增加属性"+se.getName()+",值为"+se.getValue());
- }
-
- public void attributeRemoved(HttpSessionBindingEvent se) {
-
- UserList.removeUser(String.valueOf(se.getValue()));
- System.out.println(se.getValue()+"属性已移除");
- }
-
- public void attributeReplaced(HttpSessionBindingEvent se) {
-
- String oldValue=String.valueOf(se.getValue());
- String newValue=String.valueOf(se.getSession().getAttribute(se.getName()));
- UserList.removeUser(oldValue);
- UserList.addUser(newValue);
- System.out.println(oldValue+"属性已更改为"+newValue);
- }
-
- public void sessionCreated(HttpSessionEvent se) {
-
- System.out.println("会话已创建!");
- }
-
- public void sessionDestroyed(HttpSessionEvent se) {
-
- System.out.println("会话已销毁!");
- }
-
- }
4.建立用户登录类LoginServlet.java
- package listener;
-
- import java.io.IOException;
-
- 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 LoginServlet extends HttpServlet{
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
-
- String userName=req.getParameter("userName");
- HttpSession session = req.getSession();
- session.setAttribute("userName", userName);
- resp.sendRedirect("index.jsp");
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
-
- doGet(req, resp);
- }
- }
5.建立退出登录类
- package listener;
-
- import java.io.IOException;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- public class ExitServlet extends HttpServlet{
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
-
- req.getSession().removeAttribute("userName");
- resp.sendRedirect("login.jsp");
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
-
- doGet(req, resp);
- }
- }
6.在web.xml中配置监听器、登录和退出的Servlet
-
- <listener>
- <listener-class>listener.OnlineListener</listener-class>
- </listener>
-
- <servlet>
- <servlet-name>LoginServlet</servlet-name>
- <servlet-class>listener.LoginServlet</servlet-class>
- </servlet>
- <servlet>
- <servlet-name>ExitServlet</servlet-name>
- <servlet-class>listener.ExitServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>LoginServlet</servlet-name>
- <url-pattern>/logindo</url-pattern>
- </servlet-mapping>
- <servlet-mapping>
- <servlet-name>ExitServlet</servlet-name>
- <url-pattern>/exitdo</url-pattern>
- </servlet-mapping>
7.编写index.jsp在线首页
- <body>
- <%
- //如果未登录,转向登录页面
- if (session.getAttribute("userName") == null) {
- response.sendRedirect("login.jsp");
- }
- Vector onlineUsers = UserList.getVector(); //获取存储在线用户名的vector对象
- %>
- <center>
- <br />
- <br />
- <h2>登录成功</h2>
- <hr />
- <br /> 欢迎你 <span style="color:red;"> <%=session.getAttribute("userName")%>
- </span> <a href="exitdo">退出登录</a> <br />
- <br /> 当前在线人数:<span style="color:red;"> <%=UserList.getUserCount()%>人</span>
- <br />
- <br> 在线用户名单 : <br /> <select multiple="multiple" name="list"
- style="width:200px;height:250px">
- <%
- for (int i = 0; i < onlineUsers.size(); i++) {
- out.write("<option>" + onlineUsers.get(i) + "</option>");
- }
- %>
- </select>
- </center>
- </body>
- 本文转自:http://blog.csdn.net/rongxiang111/article/details/53487381
2 0