java模擬生日發祝福


1.新建customer表生日都選為當天

所需jar包

 

2.使用c3p0連接到數據的xml配置文件

3.連接數據庫的工具類

package com.cc.birthday;

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> t1=new ThreadLocal<Connection>();
    
    //直接可以獲取一個連接池
    public static DataSource getDataSource(){
        return dataSource;
    }
    
    //獲取連接對象
    public static Connection getConnection() throws SQLException{
        Connection con=t1.get();
        if(con==null){
            con=dataSource.getConnection();
            t1.set(con);
        }
        return con;
    }
    
    //開啟事務
    public static void startTrasaction() throws SQLException {
        Connection con=getConnection();
        if(con!=null){
            con.setAutoCommit(false);
        }
    }
    
    //事務回滾
    public static void rollback() throws SQLException{
        Connection con =getConnection();
        if(con!=null){
            con.rollback();
        }
    }
    
    //提交並且 關閉資源及從ThreadLocal中釋放
    public static void commitAndRelease() throws SQLException{
        Connection con=getConnection();
        if(con!=null){
            con.commit();
            con.close();
            t1.remove();
        }
    }
    
    //關閉資源方法
    public static void closeConnection() throws SQLException{
        Connection con=getConnection();
        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();
        }
    }
    
}

4.發送郵件的工具類

package com.cc.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", "smtp.163.com");//發送郵件的服務器地址
        props.setProperty("mail.smtp.auth", "true");// 指定驗證為true

        // 創建驗證器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("emailusername", "password");//發郵件的賬號的驗證
            }
        };

        Session session = Session.getInstance(props, auth);

        // 2.創建一個Message,它相當於是郵件內容
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress("xxxxxx@163.com")); // 設置發送者

        message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 設置發送方式與接收者

        message.setSubject(subject);//郵件的主題

        message.setContent(emailMsg, "text/html;charset=utf-8");

        // 3.創建 Transport用於將郵件發送
        Transport.send(message);
    }
}

5.customer實體類

package com.cc.birthday;

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

6.根據數據庫查詢結果使用調度器定時發送祝福郵件

package com.cc.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.cc.birthday.Customer;
import com.cc.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 qr=new QueryRunner(DataSourceUtils.getDataSource());
                String sql="select * from customer where birthday like ?";
                List<Customer> customerList=null;
                try {
                     customerList = qr.query(sql, new BeanListHandler<Customer>(Customer.class),"%"+currentDate);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //2.發郵件
                if(customerList!=null&&customerList.size()>0){
                    for(Customer c:customerList){
                    String emailMsg="親愛的:"+c.getRealname()+",生日快樂!";
                    try {
                        MailUtils.sendMail(c.getEmail(), "happy..birthday", emailMsg);
                        System.out.println(c.getRealname()+"郵件發送完畢");
                    } catch (MessagingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    }
                }
            }
        },new Date(),10*1000);
        //實際開發中起始時間是一個固定的時間
        //實際開發中間隔時間是1天
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub
        
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM