JavaWeb (11)

Listener 监听器
一、Servlet事件监听器概述

1、概念

JavaWeb中的监听器是Servlet规范中定义的一种特殊类,它用于监听web应用程序中的ServletContext, HttpSession和 ServletRequest等域对象的创建与销毁事件,以及监听这些域对象中的属性发生修改的事件,并自动根据不同情况,在后台调用相应的处理程序。

通过监听器,可以自动激发一些操作,比如监听在线人数,当增加一个HttpSession时就激发 sessionCreated(HttpSessionEvent)方法,这样就可以给在线人数加1。

2、监听器类型

在Servlet规范中定义了多种类型的监听器,它们用于监听的事件源分别为 ServletContext, HttpSession 和 ServletRequest 这三个域对象。

Servlet规范针对这三个对象上的操作,又把这多种类型的监听器划分为三种类型。

  1. 监听三个域对象创建和销毁的事件监听器

  2. 监听域对象中属性的增加和删除的事件监听器

  3. 监听绑定到 HttpSession 域中的某个对象的状态的事件监听器
    在这里插入图片描述

ServletContext域对象

编写一个ServletContextListener_test类,实现ServletContextListener接口,监听ServletContext对象的创建和销毁

package com.yx.servlet.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Application Lifecycle Listener implementation class ServletContextListener_test
 * @Description:ServletContextListener_test实现了ServletContextListener接口,
 *              因此可以对ServletContext对象的创建和销毁两个动作进行监听
 */
@WebListener
public class ServletContextListener_test implements ServletContextListener {
    /**
     * Default constructor.
     */
    public ServletContextListener_test() {

    }

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent sce)  {
         System.out.println("ServletContext对象创建");
    }
    /**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent sce)  {
        System.out.println("ServletContext对象销毁");
    }
}

创建过滤器MyFiter03
使用该过滤器来获取web.xml中设置的参数

package cn.itcast.chapter08.filter;
import java.io.*;
import javax.servlet.*;
public class MyFilter03 implements Filter {
	private String characterEncoding;
	FilterConfig fc;
	public void init(FilterConfig fConfig) throws ServletException {
		// 获取FilterConfig对象
		this.fc = fConfig;
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 输出参数信息
		characterEncoding=fc.getInitParameter("encoding");
		System.out.println("encoding初始化参数的值为:"+characterEncoding);
		chain.doFilter(request, response);
	}
	public void destroy() {
	}
}

创建User类
封装用户信息

package cn.itcast.chapter08.entity;
public class User {
	private String username;
	private String password;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

创建login.jsp
用户登录的表单·

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<html>
<head></head>
<center><h3>用户登录</h3></center>
<body style="text-align: center;">
<form action="${pageContext.request.contextPath }/LoginServlet" 
method="post">
<table border="1" width="600px" cellpadding="0" cellspacing="0" 
align="center" >
	<tr>
		<td height="30" align="center">用户名:</td>
		<td>&nbsp;&nbsp;
        <input type="text" name="username" />${errerMsg }</td>
	</tr>
	<tr>
		<td height="30" align="center">密   &nbsp; 码:</td>
		<td>&nbsp;&nbsp;
          <input type="password" name="password" /></td>
	</tr>
	<tr>
		<td height="35" align="center">自动登录时间</td>
		<td><input type="radio" name="autologin" 
                  value="${60*60*24*31 }" />一个月
			<input type="radio" name="autologin" 
                  value="${60*60*24*31*3 }" />三个月
			<input type="radio" name="autologin" 
                  value="${60*60*24*31*6 }" />半年
			<input type="radio" name="autologin" 
                  value="${60*60*24*31*12 }" />一年
		</td>
	</tr>
	<tr>
		<td height="30" colspan="2" align="center">
			      <input type="submit" value="登录" />
              &nbsp;&nbsp;&nbsp;&nbsp;
			<input type="reset" value="重置" />
		</td>
	</tr>
</table>
</form>
</body>
<html>

index.jsp
显示用户登录信息

<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>显示登录的用户信息</title>
</head>
<body>
	<br />
	<center>
		<h3>欢迎光临</h3>
	</center>
	<br />
	<br />
	<c:choose>
		<c:when test="${sessionScope.user==null }">
		   <a href="${pageContext.request.contextPath }/login.jsp">用户登录</a>
		</c:when>
		<c:otherwise>
  	  欢迎你,${sessionScope.user.username }!
           <a href="${pageContext.request.contextPath }/LogoutServlet">注销</a>
		</c:otherwise>
	</c:choose>
	<hr />
</body>
</html>

LoginServlet类
处理用户的登录请求

package cn.itcast.chapter08.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import cn.itcast.chapter08.entity.User;
public class LoginServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
             HttpServletResponse response)
			throws ServletException, IOException {
		// 获得用户名和密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		// 检查用户名和密码
		if ("itcast".equals(username) && "123456".equals(password)) {
			// 登录成功
			// 将用户状态 user 对象存入 session域
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			request.getSession().setAttribute("user", user);
			// 发送自动登录的cookie
			String autoLogin = request.getParameter("autologin");
			if (autoLogin != null) {
				// 注意 cookie 中的密码要加密
				Cookie cookie = new Cookie("autologin", username + "-"
						+ password);
				cookie.setMaxAge(Integer.parseInt(autoLogin));
				cookie.setPath(request.getContextPath());
				response.addCookie(cookie);
			}
		// 跳转至首页
		response.sendRedirect(request.getContextPath()+"/index.jsp");
		} else {
			request.setAttribute("errerMsg", "用户名或密码错");
			request.getRequestDispatcher("/login.jsp")
			.forward(request,response);
		}
	}
	public void doPost(HttpServletRequest request, 
          HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

编写一个Logouservlet类
注销用户登录信息

package cn.itcast.chapter08.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class LogoutServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, 
             HttpServletResponse response)
			throws ServletException, IOException {
		// 用户注销
		request.getSession().removeAttribute("user");
		// 从客户端删除自动登录的cookie
		Cookie cookie = new Cookie("autologin", "msg");
		cookie.setPath(request.getContextPath());
		cookie.setMaxAge(0);
		response.addCookie(cookie);
		response.sendRedirect(request.getContextPath()+"/index.jsp"); 
	}
	public void doPost(HttpServletRequest request,
         HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

编写AutoLoginFilter类
拦截用户登录请求

package cn.itcast.chapter08.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import cn.itcast.chapter08.entity.User;
public class AutoLoginFilter implements Filter {
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	public void doFilter(ServletRequest req, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		// 获得一个名为 autologin 的cookie
		Cookie[] cookies = request.getCookies();
		String autologin = null;
		for (int i = 0; cookies != null && i < cookies.length; i++) {
			if ("autologin".equals(cookies[i].getName())) {
				// 找到了指定的cookie
				autologin = cookies[i].getValue();
				break;
			}
		}
		if (autologin != null) {
			// 做自动登录
			String[] parts = autologin.split("-");
			String username = parts[0];
			String password = parts[1];
			// 检查用户名和密码
			if ("itcast".equals(username)&& ("123456").equals(password)) {
				// 登录成功,将用户状态 user 对象存入 session域
				User user = new User();
				user.setUsername(username);
				user.setPassword(password);
				request.getSession().setAttribute("user", user);
			}
		}
		// 放行
		chain.doFilter(request, response);
	}
	public void destroy() {
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值