當前位置:首頁 » struts2教學 » Struts2發送Email

Struts2發送Email

Struts2發送Email郵件實例代碼和教學。

本章將教你如何使用Struts2應用程序發送電子郵件(Email)。在本練習中,您需要mail.jar的JavaMail API 1.4.4下載並安裝在你的WEB-INF\lib文件夾,並把mail.jar文件,然後繼續遵循的標準步驟創建動作,視圖和配置文件。 

創建動作- Action:

下一個步驟是創建的操作方法負責發送電子郵件。讓我們創建一個新類叫Emailer.java包含以下內容。

package com.tutorialspoint.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頁的形式中的屬性相對應的屬性。這些屬性是

  • from - 發送者的電子郵件地址。由於我們使用的是穀歌的SMTP,我們需要一個有效的gtalk ID

  • password - 上述帳戶的密碼

  • to - 誰發送的電子郵件?

  • Subject - 該電子郵件的主題

  • body - 實際的電子郵件消息

我們有冇有考慮過上述領域的任何驗證,驗證將被添加在接下來的一章。現在讓我們看看execute()方法。 execute()方法使用的javax郵件庫發送電子郵件使用提供的參數。如果郵件被發送成功,動作返回"SUCCESS",否則返回"ERROR"

創建一個主頁麵:

讓我們寫主JSP文件index.jsp,這將被用來收集電子郵件相關的上述信息:

<%@ page language="java" contentType="text/html; charset=gbk"
   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 - www.gitbook.net</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>

創建視圖:

我們將使用JSP文件的success.jsp將被調用的情況下動作返回“SUCCESS”,但返回的動作,我們將有另一種觀點認為文件中的錯誤的情況下。

<%@ 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>

下麵將視圖文件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中的配置文件如下:

<?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="com.tutorialspoint.struts2.Emailer"
         method="execute">
         <result name="success">/success.jsp</result>
         <result name="error">/error.jsp</result>
      </action>

   </package>

</struts>

以下是web.xml文件中的內容:

<?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>

現在,右鍵點擊項目名稱,並單擊“導出”> WAR文件創建一個WAR文件。然後,這WAR部署在Tomcat的webapps目錄下。最後,啟動Tomcat服務器,並嘗試訪問URL http://localhost:8080/HelloWorldStruts2/index.jsp。這會給你以下畫麵:

輸入所需信息,然後單擊“Send Email”按鈕。如果一切順利,那麼你應該看到下麵的頁麵


end over.