一、监听器Listener
1.什么是监听器?
监听器就是监听某个对象的状态变化的组件
监听器的相关概念:
事件源:被监听的对象 ----- 三个域对象 request session servletContext
监听器:监听事件源对象、事件源对象的状态的变化都会触发监听器 ---- 6+2
注册监听器:将监听器与事件源进行绑定
响应行为:监听器监听到事件源的状态变化时所涉及的功能代码 ---- 程序员编写代码
2.监听器有哪些?
第一维度:按照被监听的对象划分:ServletRequest域 HttpSession域 ServletContext域
第二维度:按监听的内容分:监听域对象的创建与销毁、监听域对象的属性变化
3.监听三大域对象的创建与销毁的监听器
监听ServletContext域的创建与销毁的监听器ServletContextListener
1)Servlet域的生命周期
何时创建:服务器启动创建
何时销毁:服务器关闭销毁
2)监听器的编写步骤(重点):
a、编写一个监听器类去实现监听器接口
b、覆盖监听器的方法
c、需要在web.xml中进行配置---注册
3)监听的方法:
package com.itheima.create;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener{
@Override
//监听context域对象的创建
public void contextInitialized(ServletContextEvent sce) {
System.out.println("context创建了....");
}
//监听context域对象的销毁
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("context销毁了....");
}
}
4)配置文件:
<listener>
<listener-class>com.itheima.create.MyServletContextListener</listener-class>
</listener>
5)ServletContextListener监听器的主要作用
a、初始化的工作:初始化对象、初始化数据 、加载数据库驱动、连接池的初始化等
b、加载一些初始化的配置文件 --- spring的配置文件
c、任务调度----定时器----Timer/TimerTask
任务调度:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String currentTime = "2016-08-19 00:00:00";
Date parse = null;
try {
parse = format.parse(currentTime);
} catch (ParseException e) {
e.printStackTrace();
}
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
System.out.println("开始了.....");
}
} , parse, 24*60*60*1000);
ServletRequest和HttpSession同上
4.监听三大域对象的属性变化的
(1)域对象的通用的方法:
setAttribute(name,value)
--- 触发添加属性的监听器的方法
--- 触发修改属性的监听器的方法
getAttribute(name)
removeAttribute(name)
--- 触发删除属性的监听器的方法
(2)ServletContextAttibuteListener监听器
package com.itheima.attribute;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
public class MyServletContextAttributeListener implements ServletContextAttributeListener{
@Override
public void attributeAdded(ServletContextAttributeEvent scab) {
//放到域中的属性
System.out.println(scab.getName());//放到域中的name
System.out.println(scab.getValue());//放到域中的value
}
@Override
public void attributeRemoved(ServletContextAttributeEvent scab) {
System.out.println(scab.getName());//删除的域中的name
System.out.println(scab.getValue());//删除的域中的value
}
@Override
public void attributeReplaced(ServletContextAttributeEvent scab) {
System.out.println(scab.getName());//获得修改前的name
System.out.println(scab.getValue());//获得修改前的value
}
}
HttpSessionAttributeListener和ServletRequestAriibuteListenr监听器(同上)
5.与session中的绑定的对象相关的监听器(对象感知监听器)
(1)即将要被绑定到session中的对象有几种状态
绑定状态:一个对象被放到session域中
解绑状态:这个对象从session域中移除
钝化状态:是将session内存中的对象持久化(序列化)到磁盘
活化状态:就是将磁盘上的对象再次恢复到session内存中
(2)绑定与解绑的监听器HttpSessionBindingListener
package com.itheima.domian;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class Person implements HttpSessionBindingListener{
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 valueBound(HttpSessionBindingEvent event) {
System.out.println("person被绑定了");
}
@Override
//解绑方法
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("person被解绑了");
}
}
(3)钝化与活化的监听器HttpSessionActivationListener
可以通过配置文件指定对象钝化时间 --- 对象多长时间不用被钝化
在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">
<Store className="org.apache.catalina.session.FileStore" directory="itheima32" />
</Manager>
</Context>
被钝化到work/catalina/localhost/的文件
二、邮箱服务器
1.邮箱服务器的基本概念
邮件客户端:可以只安装在电脑上的也可以是网页形式的
邮件服务器:邮件的接受与推送的作用
邮件发送的协议:
协议:就是数据传输的约束
接受邮件的协议:POP3 IMAP
发送邮件的协议:SMTP
2.邮箱的发送过程
5.邮件发送代码
1、导入mail.jar包
2、代码
package com.itheima.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", "12345");//发邮件的账号的验证
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]")); // 设置发送者
message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者
message.setSubject(subject);//邮件的主题
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
}
package com.itheima.birthday;
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 org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.itheima.mail.MailUtils;
public class BirthdayListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
//当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());
//根据当前时间从数据查询今天过生日的人
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from customer where birthday like ?";
List<Customer> customerList = null;
try {
customerList = runner.query(sql, new BeanListHandler<Customer>(Customer.class) ,"%"+currentDate+"%");
} catch (SQLException e) {
e.printStackTrace();
} //08-18
//2、发邮件
if(customerList!=null&&customerList.size()>0){
for(Customer c : customerList){
String emailMsg = "亲爱的:"+c.getRealname()+",生日快乐!";
try {
MailUtils.sendMail(c.getEmail(), "生日祝福", emailMsg);
System.out.println(c.getRealname()+"邮件发送完毕");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
}, new Date(), 1000*10);
//实际开发中起始时间是一个固定的时间
//实际开发中间隔时间是1天
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}