Learning log day40 (2021-09-02) (1, database connection pool 2, java sends e-mail using CommonsEmail)

Learning content: Learn Java Web (Day40)

1. Database Connection Pool
2. java uses CommonsEmail to send e-mail

1. Database Connection Pool

(1) Download dependency packages for DBCP, C3P0, DRUID, Hikaricp connection pools
DBCP: http://commons.apache.org/dbcp/
C3P0: http://sourceforge.net/projects/c3p0/
DRUID: https://druid.apache.org

(2) DBCP, DRUID, Hikaricp connection pools are configured through the db.properties file:
Create the resources directory, create a new db.properties under the directory, and mark resources as Resources Root.
Using connection pools does not require re-creating connections to the database every time. Connections can be obtained directly from the connection pool when they are needed to improve productivity.

url=jdbc:mysql://127.0.0.1/newsmanagersystem?characterEncoding=utf-8&useSSL=false
#This can be defaulted and will be automatically identified by url
driverClassName=com.mysql.jdbc.Driver
username=root
password=root

##Initial number of connections, default 0
initialSize=10
#Maximum number of connections, default 8
maxActive=30
#Minimum number of idles
minIdle=10
#Get the maximum wait time for a connection in milliseconds
maxWait=2000
#Cache PreparedStatement, default false
poolPreparedStatements=true
#Maximum number of cached PreparedStatements, default-1 (no caching).Cache PreparedStatement is automatically turned on when greater than 0, so the previous sentence can be omitted
maxOpenPreparedStatements=20

The corresponding java code is as follows:

public class jdbcUtil {
    private static DataSource dataSource;

    static {
        //Data Source Configuration
        Properties properties=new Properties();
        //Get the resource file from the class object of the current class
        InputStream is = jdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
        //Load Profile
            properties.load(is);
            //DataSource returned, not DruidDataSource
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        //Get Connections
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

(3) DBCP, DRUID, Hikaricp connection pools are configured by set method

public class DBHelp {
    //create data source
    private static HikariDataSource dataSource;
    static {
        //Read Configuration File
        try {
            InputStream is = DBHelp.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            //Load Profile
            properties.load(is);
            //Get profile information
            String driver = properties.getProperty("driverClassName");
            String url = properties.getProperty("url");
            String userName = properties.getProperty("username");
            String password = properties.getProperty("password");

            //Configure Data Source
            dataSource = new HikariDataSource();
            dataSource.setJdbcUrl(url);
            dataSource.setUsername(userName);
            dataSource.setPassword(password);
            dataSource.setDriverClassName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Get Database Connection
    public Connection getConn()  {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }
}

(4) c3p0 is configured through the c3p0-config.xml file and needs to be placed in the src folder

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <!-- Default configuration, if not specified -->
    <default-config>
        <property name="user">zhanghanlun</property>
        <property name="password">123456</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/zhanghanlun</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="checkoutTimeout">30000</property>
        <property name="idleConnectionTestPeriod">30</property>
        <property name="initialPoolSize">3</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">2</property>
        <property name="maxStatements">200</property>
    </default-config>
    <!-- Named Configuration,Can be achieved through method calls -->
    <named-config name="test">
        <property name="user">zhanghanlun</property>
        <property name="password">123456</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/zhanghanlun</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <!-- How many connections to grow at a time if there are not enough data connections in the pool -->
        <property name="acquireIncrement">5</property>
        <!-- Number of connections when initializing the database connection pool -->
        <property name="initialPoolSize">20</property>
        <!-- Maximum number of database connections in the database connection pool -->
        <property name="maxPoolSize">25</property>
        <!-- Minimum number of database connections in the database connection pool -->
        <property name="minPoolSize">5</property>
    </named-config>
</c3p0-config>

Corresponding java code:

//Load a configuration file with the name "test"
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource("test");
    /**
     * Get Connection Connection Connection
     * @return
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

(5) c3p0 is configured by set method

private static ComboPooledDataSource dataSource = new ComboPooledDataSource();
    /**
     * Configure DataSource
     */
    public static void configDataSource(){
        try {
            dataSource.setDriverClass("com.mysql.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/zhanghanlun");
            dataSource.setUser("zhanghanlun");
            dataSource.setPassword("123456");
            dataSource.setInitialPoolSize(3);
            dataSource.setMaxPoolSize(10);
            dataSource.setMinPoolSize(3);
            dataSource.setAcquireIncrement(3);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }
    /**
     * Get Connection Connection Connection
     * @return
     */
    public static Connection getConnection(){
        Connection conn = null;
        configDataSource();
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

2. java uses CommonsEmail to send e-mail

(1) Apache Commons Email provides an API for sending e-mail.It is built on the JavaMail API to simplify it.
Sending mailbox using commos-email.jar requires three jar packages to be imported first
commos-email.jar
mail.jar
activation-1.1.jar

(2) What you need to know to send mail
* Mail Server Address * Mail Server Port * Do I need to verify * Sender Address * Sender User Name * Sender Password * Recipient Address * Mail Subject * Mail Content * Attachments

(3) Mail Receiving and Sending Protocol
The protocol used to send mail is SMTP, and the port number used is 25
The protocol used to receive mail is POP3, and the port number used is 110

(4) Before sending mail by encoding, first modify the mailbox configuration, go to the official website to log in to the mailbox account, select the POP3/SMTP/IMAP option in the settings, and open the service. You will be prompted to enter the authorization code, remember the set authorization code, which is the sender's password for sending mail by commons-email.You can then write code.

(5) commons-email to send ordinary text mail

Email email = new SimpleEmail(); //New Normal Text Mail Object
email.setHostName("smtp.163.com"); //sender address
email.setAuthentication("yang7email@163.com", "nhrxjldwmpxlbdch"); //Sender User Name and Authorization Number
email.setCharset("UTF-8");//Encoding Format 
email.setTLS(true);//Whether to use TLS security protocol 
try {
    email.setFrom("743351804@qq.com"); //Sender Mailbox
    email.setSubject("commons email"); //Subject Sent
    email.setMsg("This is a plain text message"); //Sent Content
    email.addTo("1064289281@qq.com"); //Recipient Mailbox
    email.send(); //Send out
} catch (EmailException e) { 
    e.printStackTrace(); 
}

(6) commons-email to send HTML mail

HtmlEmail email = new HtmlEmail();//New HTML Mail Object
email.setHostName("smtp.163.com");
email.setAuthentication("yang7email@163.com", "ROBQTYBQTQVSQVNW");
email.setCharset("UTF-8");
email.setTLS(true);
try {
    email.setFrom("yang7email@163.com");
    email.setSubject("Win the prize");
    //Send an html message to add a style.Can send pictures, picture address must be server url address
    email.setHtmlMsg("<div style = \"font-weight:blod;color:red;\">Five million</div><img src = \"https://pic3.pocoimg.cn/image/poco/works/17/2021/0222/14/16139751885578129_178285158.jpg\">");
    email.addTo("1768374916@qq.com");
    email.send();
} catch (EmailException e) {
    e.printStackTrace();
}

(7) commons-email to send mail with attachments

MultiPartEmail email = new MultiPartEmail();//New mail object with attachments

EmailAttachment ea = new EmailAttachment();//Attachments to send
ea.setPath("d:/pic/1.jpg");

email.setHostName("smtp.163.com");
email.setAuthentication("yang7email@163.com", "ROBQTYBQTQVSQVNW");
email.setCharset("UTF-8");
email.setTLS(true);
try {
    email.setFrom("yang7email@163.com");
    email.setSubject("Win the prize");
    email.setMsg("<div style = \"font-weight:blod;color:red;\">Five million</div><img src = \"https://pic3.pocoimg.cn/image/poco/works/17/2021/0222/14/16139751885578129_178285158.jpg\">");
    email.addTo("1768374916@qq.com");
    email.attach(ea);  //Add Attachments to Mail
    email.send();
} catch (EmailException e) {
    e.printStackTrace();
}

(8) Create a tool class, EmailUtil.java, to send mail of different types

public class EmailUtil {
    //Set Default Value
    private static String hostName = "smtp.163.com";
    private static String userName = "yang7email@163.com";
    private static String password = "ROBQTYBQTQVSQVNW";
    private static String from = "yang7email@163.com";
    private static String character = "UTF-8";

    static {//Initialization using static blocks
        try {
        //Getting mapping of email.properties using input streams
            InputStream is = EmailUtil.class.getClassLoader().getResourceAsStream("email.properties");
            Properties properties = new Properties();
            //Load Input Stream
            properties.load(is);
            //Get profile information
            if(properties.getProperty("email_hsotName") != null){
                hostName = properties.getProperty("email_hostName");
            }

            if(properties.getProperty("email_userName") != null){
                userName = properties.getProperty("email_userName");
            }
            if(properties.getProperty("email_password") != null){
                password = properties.getProperty("email_password");
            }
            if(properties.getProperty("email_from") != null){
                from = properties.getProperty("email_from");
            }

            if(properties.getProperty("email_charset") != null){
                character = properties.getProperty("email_charset");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void sendTxtEmail(String toEmail,String subject,String content){
        Email email = new SimpleEmail();
        email.setHostName(hostName);
        email.setAuthentication(userName, password);
        email.setCharset(character);
        email.setTLS(true);
        try {
            email.setFrom(from);
            email.setSubject(subject);
            email.setMsg(content);
            email.addTo(toEmail);
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }
    
    public static void sendHtmlEmail(String toEmail,String subject,String content){
        HtmlEmail email = new HtmlEmail();
        email.setHostName(hostName);
        email.setAuthentication(userName, password);
        email.setCharset(character);
        email.setTLS(true);
        try {
            email.setFrom(from);
            email.setSubject(subject);
            email.setHtmlMsg(content);
            email.addTo(toEmail);
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }

    public static void sendAttacheEmail(String path,String toEmail,String subject,String content){
        MultiPartEmail email = new MultiPartEmail();

        EmailAttachment ea = new EmailAttachment();
        ea.setPath(path);

        email.setHostName(hostName);
        email.setAuthentication(userName, password);
        email.setCharset(character);
        email.setTLS(true);
        try {
            email.setFrom(from);
            email.setSubject(subject);
            email.setMsg(content);
            email.addTo(toEmail);
            email.attach(ea);
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }
}

Create Email.properties file for configuration

email_hostName=smtp.163.com
email_userName=yang7email@163.com
email_password=ROBQTYBQTQVSQVNW
email_charset=UTF-8
email_from=yang7email@163.com

test

public static void main(String[] args) {
    EmailUtil.sendTxtEmail("1768374916@qq.com","hehe","hahha");
}

(9) Send activation mail at the time of registration, and the user clicks on the mail link to send activation code to the server to verify that the registration is successful.
Create Tool Class CodeUtil to Randomly Generate 6-bit Authentication Codes

public class CodeUtil {

    public static String getCode(){
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb=new StringBuilder(6);
        for(int i=0;i<6;i++)
        {
            char ch=str.charAt(new Random().nextInt(str.length()));
            sb.append(ch);
        }
        return sb.toString();
    }
}

servlet class

@WebServlet("/user/api/v1")
public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1. Register an account
        //2. Get the verification code jlfadskf
        String code = CodeUtil.getCode();
        //3. Save the database

        //Sending mail wastes time. New thread sends mail
        Thread th = new Thread(new Runnable() {
           @Override
           public void run() {
               //The activation mail is sent at the time of registration, and the user clicks on the mail link to send the activation code to the server to verify that the registration is successful.
               EmailUtil.sendTxtEmail("1768374916@qq.com", "Registration Activation", "http://localhost/active?code=" + code);
           }
        });
        th.start();
    }
}

Keywords: Java Database

Added by andreas on Thu, 02 Sep 2021 19:32:27 +0300