Struts2 發(fā)送電子郵件

2020-06-15 19:26 更新

本章內(nèi)容將教你如何使用Struts2 應(yīng)用程序發(fā)送電子郵件。學(xué)習(xí)前,你需要從JavaMail API 1.4.4下載并安裝mail.jar,并將mail.jar文件放在WEB-INF\lib文件夾中,然后繼續(xù)按照以下標(biāo)準(zhǔn)步驟創(chuàng)建action,視圖和配置文件。

創(chuàng)建Action

首先是創(chuàng)建一個(gè)Action方法來處理電子郵件發(fā)送。讓我們創(chuàng)建一個(gè)包含以下內(nèi)容的名為Emailer.java的新類:

package cn.w3cschool.struts2;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.opensymphony.xwork2.ActionSupport;

public class Emailer extends ActionSupport {

   private String from;
   private String password;
   private String to;
   private String subject;
   private String body;

   static Properties properties = new Properties();
   static
   {
      properties.put("mail.smtp.host", "smtp.gmail.com");
      properties.put("mail.smtp.socketFactory.port", "465");
      properties.put("mail.smtp.socketFactory.class",
                     "javax.net.ssl.SSLSocketFactory");
      properties.put("mail.smtp.auth", "true");
      properties.put("mail.smtp.port", "465");
   }

   public String execute() 
   {
      String ret = SUCCESS;
      try
      {
         Session session = Session.getDefaultInstance(properties,  
            new javax.mail.Authenticator() {
            protected PasswordAuthentication 
            getPasswordAuthentication() {
            return new 
            PasswordAuthentication(from, password);
            }});

         Message message = new MimeMessage(session);
         message.setFrom(new InternetAddress(from));
         message.setRecipients(Message.RecipientType.TO, 
            InternetAddress.parse(to));
         message.setSubject(subject);
         message.setText(body);
         Transport.send(message);
      }
      catch(Exception e)
      {
         ret = ERROR;
         e.printStackTrace();
      }
      return ret;
   }

   public String getFrom() {
      return from;
   }

   public void setFrom(String from) {
      this.from = from;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

   public String getTo() {
      return to;
   }

   public void setTo(String to) {
      this.to = to;
   }

   public String getSubject() {
      return subject;
   }

   public void setSubject(String subject) {
      this.subject = subject;
   }

   public String getBody() {
      return body;
   }

   public void setBody(String body) {
      this.body = body;
   }

   public static Properties getProperties() {
      return properties;
   }

   public static void setProperties(Properties properties) {
      Emailer.properties = properties;
   }
}

如上面的源代碼所示,Emailer.java具有與下面給出的email.jsp頁面中的表單屬性相對(duì)應(yīng)的屬,這些屬性分別是:

  • from - 發(fā)件人的電子郵件地址。由于我們使用Google的SMTP,因此我們需要有效的gtalk ID。

  • password - 上述帳戶的密碼

  • to - 發(fā)送電子郵件給誰?

  • Subject - 電子郵件的主題

  • body - 實(shí)際的電子郵件內(nèi)容

我們沒有考慮對(duì)上述字段的任何驗(yàn)證,驗(yàn)證將在下一章添加。讓我們看看execute()方法, execute()方法使用javax Mail庫提供的參數(shù)發(fā)送電子郵件。如果郵件成功發(fā)送,action返回SUCCESS,否則返回ERROR。

創(chuàng)建主頁

現(xiàn)行編寫主頁的JSP文件index.jsp,這將用于收集上面提到的電子郵件相關(guān)信息:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Email Form</title>
</head>
<body>
   <em>The form below uses Google's SMTP server. 
   So you need to enter a gmail username and password
   </em>
   <form action="emailer" method="post">
   <label for="from">From</label><br/>
   <input type="text" name="from"/><br/>
   <label for="password">Password</label><br/>
   <input type="password" name="password"/><br/>
   <label for="to">To</label><br/>
   <input type="text" name="to"/><br/>
   <label for="subject">Subject</label><br/>
   <input type="text" name="subject"/><br/>
   <label for="body">Body</label><br/>
   <input type="text" name="body"/><br/>
   <input type="submit" value="Send Email"/>
   </form>
</body>
</html>

創(chuàng)建視圖

現(xiàn)在創(chuàng)建success.jsp文件,這在action返回SUCCESS結(jié)果的情況下會(huì)被調(diào)用,但如果從action返回ERROR結(jié)果,我們將用另一個(gè)視圖文件。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Email Success</title>
</head>
<body>
   Your email to <s:property value="to"/> was sent successfully.
</body>
</html>

以下將是在action返回ERROR的情況下調(diào)用的視圖文件error.jsp。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Email Error</title>
</head>
<body>
   There is a problem sending your email to <s:property value="to"/>.
</body>
</html>

配置文件

最后,讓我們使用struts.xml配置文件將所有內(nèi)容放在一起,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

   <constant name="struts.devMode" value="true" />
   <package name="helloworld" extends="struts-default">

      <action name="emailer" 
         class="cn.w3cschool.struts2.Emailer"
         method="execute">
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>

   </package>

</struts>

以下是web.xml文件的內(nèi)容:

<?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" 
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="WebApp_ID" version="3.0">
   
   <display-name>Struts 2</display-name>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
      <filter-name>struts2</filter-name>
      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

現(xiàn)在,右鍵單擊項(xiàng)目名稱,然后單擊“Export”> “WAR File”以創(chuàng)建WAR文件。然后在Tomcat的webapps目錄中部署WAR文件。最后,啟動(dòng)Tomcat服務(wù)器并嘗試訪問URL http://localhost:8080/HelloWorldStruts2/index.jsp,將顯示以下界面:

電子郵件用戶輸入

輸入所需的信息,然后單擊Send Email按鈕。如果一切正常,那么你可以看到以下頁面:

電子郵件成功

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)