JavaWeb——Listener(监听器)
1、什么是监听器
监听器就是监听某个对象的的状态变化的组件。
监听器的相关概念:
事件源:被监听的对象 —– 三个域对象 request session servletContext
监听器:监听事件源对象 事件源对象的状态的变化都会触发监听器 —- 6+2
注册监听器:将监听器与事件源进行绑定
响应行为:监听器监听到事件源的状态变化时 所涉及的功能代码 —- 程序员编写代码
2、8个监听器
第一维度:按照被监听的对象划分:ServletRequest域 HttpSession域 ServletContext域
第二维度:监听的内容分:监听域对象的创建与销毁的 监听域对象的属性变化的
1、绑定与解绑的监听器HttpSessionBindingListener
2、钝化与活化的监听器HttpSessionActivationListener
3、监听器对象
3.1 域对象(以ServletContextListener为例)
Servlet域的生命周期
何时创建:服务器启动创建
何时销毁:服务器关闭销毁
创建ServletContextListener监听器
package cn.ctgu.create;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class MyServletContextListener implements ServletContextListener{
@Override
//监听context域对象的创建
public void contextInitialized(ServletContextEvent sc) {
// TODO Auto-generated method stub
/* //就是被监听的对象————ServletContext
ServletContext servletContext=sc.getServletContext();
System.out.println("context创建了...");*/
/*//getSource就是被监听的对象,是通用的方法
Object source=sc.getSource();*/
//开启一个计息任务调度——————每天晚上12点计息一次
Timer timer=new Timer();
//task:任务 firstTime:第一次执行时间 period:间隔执行时间
//timer..scheduleAtFixedRate(task,firstTime,period);
/*timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("银行计息了。。。。。。");
}
}, new Date(), 5000);*/
//改成银行真正计息
/*1、起始时间:定义成晚上12点
* 2、间隔时间:24小时
*
* */
//设置第一次计息时间为晚上十二点
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String currentTime="2018-04-04 00:00:00";
Date parse=null;
try {
parse=format.parse(currentTime);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("银行计息了。。。。。。");
}
}, parse, 24*3600*1000);
}
@Override
//监听context域对象的销毁
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}
ServletContextListener监听器的主要作用
a、初始化的工作:初始化对象 初始化数据 —- 加载数据库驱动 连接池的初始化
b、加载一些初始化的配置文件 — spring的配置文件
c、任务调度—-定时器—-Timer/TimerTask
3.2 HttpSessionListener
HttpSession对象的生命周期:
何时创建:第一次调用request.getSession时创建
何时销毁:服务器关闭销毁 session过期 手动销毁
package cn.ctgu.create;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class MyHttpSessionListener implements HttpSessionListener{
@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("session创建"+se.getSession().getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
}
3.3 ServletRequestListener
ServletRequest的生命周期
创建:每一次请求都会创建request
销毁:请求结束
3.4 监听三大域对象的属性变化的监听器
域对象的通用的方法:
setAttribute(name,value)
— 触发添加属性的监听器的方法
— 触发修改属性的监听器的方法
getAttribute(name)
removeAttribute(name)
— 触发删除属性的监听器的方法
package cn.ctgu.attribute.create;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServletContexAttributeListener
*/
@WebServlet(“/TestServletContexAttributeListener”)
public class TestServletContexAttributeListener extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext context=this.getServletContext();
//向context域中存数据
context.setAttribute("name", "Tom");
//改context数据
context.setAttribute("name", "lucy");
//删除context数据
context.removeAttribute("name");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
package cn.ctgu.attribute.create;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class MyServletContextAttributeListener implements ServletContextAttributeListener{
@Override
public void attributeAdded(ServletContextAttributeEvent sc) {
//放到域中的属性
System.out.println(sc.getName());//放到域中的name
System.out.println(sc.getValue());//放到域中的value
}
@Override
public void attributeRemoved(ServletContextAttributeEvent sc) {
System.out.println(sc.getName());//删除域中的name
System.out.println(sc.getValue());//删除域中的value
}
@Override
public void attributeReplaced(ServletContextAttributeEvent sc) {
System.out.println(sc.getName());//获得修改前的域中的name
System.out.println(sc.getValue());//获得修改前的域中的value
}
}
HttpSessionAttributeListener监听器、ServletRequestAriibuteListenr监听器(同上)
3.5 与session中的绑定的对象相关的监听器(对象感知监听器)
即将要被绑定到session中的对象有几种状态
绑定与解绑的监听器HttpSessionBindingListener:
绑定状态:就一个对象被放到session域中
解绑状态:就是这个对象从session域中移除了
钝化与活化的监听器HttpSessionActivationListener:
钝化状态:是将session内存中的对象持久化(序列化)到磁盘
活化状态:就是将磁盘上的对象再次恢复到session内存中
3.5.1 HttpSessionBindingListener
被绑定对象Person类:
Person.java
package cn.ctgu.attribute.domain;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class Person implements HttpSessionBindingListener{
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//绑定方法,session将person对象添加的时候触发
@Override
public void valueBound(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
System.out.println("person被绑定了");
}
//解绑方法,session将person移除掉的时候触发
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
// TODO Auto-generated method stub
System.out.println("person被解绑了");
}
}
TestPersonBindingServlet.java
package cn.ctgu.attribute.domain;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class TestPersonBindingServlet
*/
@WebServlet("/TestPersonBindingServlet")
public class TestPersonBindingServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
//将person对象绑定到session中
Person p=new Person();
p.setId(100);
p.setName("zhangsanfeng");
session.setAttribute("person",p);
//将person对象从session中解绑
session.removeAttribute("person");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
3.5.2 HttpSessionActivationListener
被钝化和活化的Customer类
Customer.java
package cn.ctgu.attribute.domain;
import java.io.Serializable;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;
//实现了Serializable接口才能被活化(序列化)
public class Customer implements HttpSessionActivationListener,Serializable{
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//活化
@Override
public void sessionDidActivate(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Customer被活化了");
}
//钝化
@Override
public void sessionWillPassivate(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Customer被钝化了");
}
}
META-INF目录下的context.xml文件配置钝化路径以及钝化间隔时间
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- maxIdleSwap:session中的对象多长时间不使用就钝化 -->
<!-- directory:钝化后的对象的文件写到磁盘的哪个目录下 配置钝化的对象文件在 work/catalina/localhost/钝化文件 -->
<Manager className="org.apache.catalina.session.PersistentManager"
maxIdleSwap="1"><!--这里的1表示1分钟,即session 1分钟不用的时候对象就会被钝化到磁盘 -->
<Store className="org.apache.catalina.session.FileStore"
directory="C:\Users\Administrator\Desktop\Java\JavaWeb\Listener\SessionActivation" />
<!--这里的directory表示session钝化后的存储路径 -->
</Manager>
</Context>
TestCustomerHttpSessionActivationListener.java
package cn.ctgu.attribute.domain;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class TestCustomerHttpSessionActivationListener
*/
@WebServlet("/TestCustomerHttpSessionActivationListener")
public class TestCustomerHttpSessionActivationListener extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
//将customer放到session中,当服务器关闭的时候customer对象就会被钝化到磁盘中
Customer customer=new Customer();
customer.setId("200");
customer.setName("lucy");
session.setAttribute("customer", customer);
System.out.println("customer被放到session域中");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
TestCustomerHttpSessionActivationListener2.java
package cn.ctgu.attribute.domain;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class TestCustomerHttpSessionActivationListener2
*/
@WebServlet("/TestCustomerHttpSessionActivationListener2")
public class TestCustomerHttpSessionActivationListener2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从session域中获得customer,只有服务器重启的时候,session域中的被钝化的对象,才能从磁盘中活化过来被使用
HttpSession session=request.getSession();
Customer customer=(Customer)session.getAttribute("customer");
System.out.println(customer.getName());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
4、邮箱服务器
1.邮箱服务器的基本概念
邮件的客户端:可以只安装在电脑上的也可以是网页形式的
邮件服务器:起到邮件的接受与推送的作用
邮件发送的协议:
协议:就是数据传输的约束
接受邮件的协议:POP3 IMAP
发送邮件的协议:SMTP
2.邮箱的发送过程
5、案例——定时发送生日祝福邮件
Customers.java
package cn.ctgu.birthday;
public class Customers {
private int id;
private String username;
private String password;
private String realname;
private String birthday;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
JDBCUtilsConfig.java
package cn.ctgu.dao;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/*
* 编写JDBC的工具类,获取数据库的连接对象采用
* 采用读取配置文件的方式
* 读取文件获取连接,执行一次,采用static代码块,
*
* */
public class JDBCUtilsConfig {
private static Connection con;
private static String driverClass;
private static String url;
private static String username;
private static String password;
static {
try {
readConfig();
Class.forName(driverClass);
con=DriverManager.getConnection(url, username, password);
}catch(Exception e) {
throw new RuntimeException("数据库连接失败");
}
}
private static void readConfig() throws Exception{
InputStream in=JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
Properties pro=new Properties();
pro.load(in);
driverClass=pro.getProperty("driverClass");
url=pro.getProperty("url");
username=pro.getProperty("username");
password=pro.getProperty("password");
}
public static Connection getConnection() {
return con;
}
}
database.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybase
username=root
password=123456
MailUtils.java
package cn.ctgu.mail;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class MailUtils {
//email:邮件发给谁 subject:代表主题 emailMsg:代表内容
public static void sendMail(String email, String subject,String emailMsg)
throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");//发邮件协议
props.setProperty("mail.host", "localhost");//发送邮件的服务器地址
props.setProperty("mail.smtp.auth", "true");// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("tom", "123456");//发邮件的账号的验证
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("aaa@qq.com")); // 设置发送者
message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者
message.setSubject(subject);//设置邮件的主题
// message.setText("这是一封**邮件,请<a href='#'>点击</a>");
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
}
BirthdayListener.java
package cn.ctgu.birthday;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.mail.MessagingException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import cn.ctgu.dao.JDBCUtilsConfig;
import cn.ctgu.mail.MailUtils;
@WebListener
public class BirthdayListener implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
//当web应用启动,开启任务调动————功能在用户的生日前发送邮件
//开启一个定时器
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// 为当前的生日的用户发邮件
//1、获得今天过生日的人
//获得今天的日期
SimpleDateFormat format=new SimpleDateFormat("MM-dd");
String currentDate=format.format(new Date());
//根据当前时间从数据库查询今天过生日的人
Connection con=JDBCUtilsConfig.getConnection();
QueryRunner runner=new QueryRunner();
String sql="select * from customer where birthday like?";
List<Customers>customerList=null;
try {
customerList=runner.query(con, sql, "%"+currentDate+"%", new BeanListHandler<Customers>(Customers.class));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//2、发邮件
if(customerList!=null&&customerList.size()>0) {
for(Customers c:customerList) {
String emailMsg="亲爱的"+c.getRealname()+",生日快乐!";
try {
MailUtils.sendMail(c.getEmail(),"生日祝福", emailMsg);
System.out.println(c.getRealname()+"邮件发送完毕");
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}, new Date(), 1000*5);
//实际开发中起始时间是一个固定的时间
//实际开发中间隔时间是1天
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}