java 使用监听器完成定时生日祝福

监听ServletContext域的创建与销毁的监听器ServletContextListener

1.Servlet域的生命周期:

何时创建:服务器启动创建

何时销毁:服务器关闭销毁

2.监听器的编写步骤:

(1)编写一个监听器类去实现监听器接口

(2)覆盖监听器的方法

(3)需要在web.xml中进行配置---注册

Customer主体

package domain;

public class Customer {

	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;
	}
	@Override
	public String toString() {
		return "Customer [id=" + id + ", username=" + username + ", password=" + password + ", realname=" + realname
				+ ", birthday=" + birthday + ", email=" + email + "]";
	}
	
	
	
}

编写类继承ServletContextListener,覆盖监听器的方法

package web;

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 Utils.MailUtils;
import domain.Customer;
import service.birthdayService;

public class SendBirthday implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("销毁。。。。");
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {
				SimpleDateFormat format = new SimpleDateFormat("MM-dd");
				String currentDate = format.format(new Date());
				System.out.println("currentDate:"+currentDate);
				birthdayService birthdayService = new birthdayService();
				List<Customer> allCustomer = null;
				try {
                    //传入当前时间,获取list集合,此步为从数据库获取Customer集合
					allCustomer = birthdayService.getCustomer(currentDate);
				} catch (SQLException e) {
					e.printStackTrace();
				}
				if(allCustomer!=null&&allCustomer.size()>0) {
					for(Customer c:allCustomer) {
						System.out.println("C:"+c.toString());
						String emailMsg = "dear"+c.getRealname()+"hello birthday";
						try {
							MailUtils.sendMail(c.getEmail(), "test02", emailMsg);
							System.out.println("ok");
						} catch (MessagingException e) {
							// TODO Auto-generated catch block
							System.out.println("NO");
							e.printStackTrace();
						}
					}
				}
				
			}
		}, new Date(), 1000*20);
		
	}

}

web.xml

listener-class   包名+类名   web.SendBirthday

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  
  <listener>
  	<listener-class>web.SendBirthday</listener-class>
  </listener>
  <display-name>webTest</display-name>
  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>Birthday</display-name>
    <servlet-name>Birthday</servlet-name>
    <servlet-class>web.Birthday</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Birthday</servlet-name>
    <url-pattern>/birthday</url-pattern>
  </servlet-mapping>
</web-app>

MailUtils是发送邮件工具类

package Utils;

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;
/*
 * email:邮件发给谁
 *  subject:主题
 *  emailMsg:邮件的内容
 */
public class MailUtils {

	
	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");//发送邮件的服务器地址   外网发邮件需要修改mail.host如 SMTP服务器: smtp.163.com
		props.setProperty("mail.smtp.auth", "true");// 指定验证为true

		// 创建验证器
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("jack", "123");//发邮件的账号的验证[email protected]   填入用户名和授权码   注意是授权码
			}
		};

		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);
	}
	
	
}

猜你喜欢

转载自blog.csdn.net/qq_41566772/article/details/84991824