javaWeb之自动发送邮件生日祝福(ServletContextListener监听)
在看完本随笔仍然不理解的可以看 javaWeb邮箱发送 :里面有具体的邮箱服务器配置
企业在员工生日当天发送邮箱生日祝福:
一般是用监听器完成: 而合适的监听是ServletContextListener ,每天都定时查看该天过生日的员工,并发送邮件祝福
创建一个监听器:
package com.study.mail; 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.mail.internet.AddressException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler; import com.study.utils.DataSourceUtils; public class MyServletContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent arg0) {
Timer timer=new Timer();
final SimpleDateFormat sdf=new SimpleDateFormat("MM-dd");
final QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
timer.schedule(new TimerTask() {
@Override
public void run() { //判断今天的日期
String today="\"%"+sdf.format(new Date())+"%\"";
// today 容易写成 "%"+sdf.format(new Date())+"%"
// 导致生成的sql语句为: select * from user where birthday like %11-13%
// 正常运行的sql语句为: select * from user where birthday like "%11-13%",
//因此使用 ‘\’ 转义符把 " 转化 //今天生日的员工
String sql="select * from user where birthday like "+today;
List<User> userList =null;
try {
System.out.println(sql);
userList = qr.query(sql, new BeanListHandler<User>(User.class));
} catch (SQLException e) {
e.printStackTrace();
}
if (userList!=null) {
for (User user : userList) {
String emailMsg="亲爱的"+user.getName()+"<br/>祝你生日快乐";
try {
MailUtils.sendMail(user.getEmail(), "生日祝福", emailMsg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
}
}, new Date(), 1000*5);
//new Date() 具体的项目不为这个, 1000*5 // 真正项目是1000*60*60*24 一天
} public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
} }
User 类:
package com.study.mail;
public class User {
private String name;
private String passWord;
private String email;
private String birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
MailUtils类:
package com.study.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 { 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("tom@study.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);
}
}
DataSourceUtils类
package com.study.utils; import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DataSourceUtils { private static DataSource dataSource = new ComboPooledDataSource(); private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); // 直接可以获取一个连接池
public static DataSource getDataSource() {
return dataSource;
} public static Connection getConnection() throws SQLException{
return dataSource.getConnection();
} // 获取连接对象
public static Connection getCurrentConnection() throws SQLException { Connection con = tl.get();
if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}
return con;
} // 开启事务
public static void startTransaction() throws SQLException {
Connection con = getCurrentConnection();
if (con != null) {
con.setAutoCommit(false);
}
} // 事务回滚
public static void rollback() throws SQLException {
Connection con = getCurrentConnection();
if (con != null) {
con.rollback();
}
} // 提交并且 关闭资源及从ThreadLocall中释放
public static void commitAndRelease() throws SQLException {
Connection con = getCurrentConnection();
if (con != null) {
con.commit(); // 事务提交
con.close();// 关闭资源
tl.remove();// 从线程绑定中移除
}
} // 关闭资源方法
public static void closeConnection() throws SQLException {
Connection con = getCurrentConnection();
if (con != null) {
con.close();
}
} public static void closeStatement(Statement st) throws SQLException {
if (st != null) {
st.close();
}
} public static void closeResultSet(ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
} }
C3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="user">root</property>
<property name="password">root</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///WEBListener</property>
</default-config>
</c3p0-config>
mysql数据库:

foxmail用户

应用开启:生日当天的user收到邮件

javaWeb之自动发送邮件生日祝福(ServletContextListener监听)的更多相关文章
- springBoot高级:自动配置分析,事件监听,启动流程分析,监控,部署
知识点梳理 课堂讲义 02-SpringBoot自动配置-@Conditional使用 Condition是Spring4.0后引入的条件化配置接口,通过实现Condition接口可以完成有条件的加载 ...
- JavaWeb学习记录(二十七)——定时发送邮件ServletContextListener监听实现
public class EmailSendListener implements ServletContextListener{ @Override public void contextDe ...
- javaweb监听
监听项目启动 package com.java7115.quartz; import javax.servlet.ServletContextEvent; import javax.servlet.S ...
- 涂抹Oracle笔记1-创建数据库及配置监听程序
一.安装ORACLE数据库软件及创建实例OLTP:online transaction processing 指那些短事务,高并发,读写频繁的数据库系统.--DB_BLOCK_SIZE通常设置较小.O ...
- 如何让oracle DB、监听和oem开机启动(dbstart)
如何让oracle DB.监听和oem开机启动(dbstart) 让oracle DB.监听和oem开机启动(dbstart) Oracle提供了伴随操作系统自动重启的功能,在Windows中,可以修 ...
- 监听Web容器启动与关闭
在Servlet API 中有一个 ServletContextListener 接口,它能够监听 ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期. 要监听web ...
- 使用cordova,监听安卓机物理返回按键,实现退出程序的功能
在使用html5开发app时,并不能像Android原生那样调取手机自身的方法.而cordova正好弥补了html5这一缺陷. 一,在cordova中文网http://cordova.axuer.co ...
- JavaWeb监听器的使用(一)监听上下文和会话信息
1.监听上下文的类 package com.examp.ch9; import java.io.FileOutputStream; import java.io.PrintWriter; import ...
- Java线程监听,意外退出线程后自动重启
Java线程监听,意外退出线程后自动重启 某日,天朗气清,回公司,未到9点,刷微博,顿觉问题泛滥,惊恐万分! 前一天写了一个微博爬行程序,主要工作原理就是每隔2分钟爬行一次微博,获取某N个关注朋友微博 ...
随机推荐
- java对象序列化、反序列化
平时我们在Java内存中的对象,是无法进行IO操作或者网络通信的,因为在进行IO操作或者网络通信的时候,人家根本不知道内存中的对象是个什么东西,因此必须将对象以某种方式表示出来,即存储对象中的状态.一 ...
- Spring整合JMS(一)-基础篇
1.基础知识 图1 同步通信和异步通信通信过程示意图 RMI使用的是同步通信,JMS使用的是异步通信.从图1可以看出异步通信的好处就是减少了不必要的等待,提高了效率. JMS中有两个主要的概念:消 ...
- OI黑科技:读入优化
利用getchar()函数加速读入. Q:读入优化是什么? A :更加快速地读入一些较大的数字. Q:scanf不是已经够快了吗? A:Naive,scanf还是不!够!快! Q:那怎么办呢? A:我 ...
- ASP.NET Core 发布 centos7 配置守护进程
ASP.NET Core应用程序发布linux在shell中运行是正常的.可一但shell关闭网站也就关闭了,所以要配置守护进程, 用的是Supervisor,本文主要记录配置的过程和过程遇到的问题 ...
- 【Oracle】-初识PL/SQL
在最近的工作中要用到存储过程和函数,索性把PL/SQL整体的看一下.之前看过基本书和园子里的博文,在这里将所学简单总结. 一.基本语句 1.大小写 2.分隔符 -- : 3.引用字符串 -- ...
- C# 快速高效率复制对象的几种方式
http://www.cnblogs.com/emrys5/p/expression_trans_model.html 这篇较具体. 本文基于上文略加改动,暂记 using Newtonsoft.Js ...
- 箱型图boxplot函数的使用
主要参数: medlwd:设置中位线宽度 whiskcol:设置虚线颜色 staplecol:设置顶端颜色 outcol:离群值颜色 相应的具体位置: outline=FALSE:去除离群值 outp ...
- Mysql利用存储过程插入400W条数据
CREATE TABLE dept( /*部门表*/ deptno MEDIUMINT UNSIGNED NOT NULL DEFAULT 0, /*编号*/ dname VARCHAR(20) NO ...
- java字符串以及字符类型基础
介绍一下java字符集和字符的编码方式, 首先要区分一下字符集和字符编码.所谓的字符集 类似于unicode,GB2312,GBK,ASCII等等.因为一开始只有26个英文字母需要 编一下号.所有用下 ...
- hihoCoder 1036 Trie图 AC自动机
题意:给定n个模式串和一个文本串,判断文本中是否存在模式串. 思路:套模板即可. AC代码 #include <cstdio> #include <cmath> #includ ...