Listener監聽器

一、監聽器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) {
		
	}

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章