鍍金池/ 教程/ Java/ 發(fā)送郵件
注釋
主題/模板
驗(yàn)證
有用的資源
Struts 2 注解類型
實(shí)例
攔截器
異常處理
表單標(biāo)簽
結(jié)果類型
值棧/OGNL
Spring 集成
數(shù)據(jù)標(biāo)簽
環(huán)境配置
配置
類型轉(zhuǎn)換
動(dòng)作
Hibernate 集成
本地化
發(fā)送郵件
Ajax 標(biāo)簽
數(shù)據(jù)庫(kù)訪問(wèn)
體系結(jié)構(gòu)
文件上傳
Tiles 集成
概述
基本的 MVC 架構(gòu)
控制標(biāo)簽

發(fā)送郵件

本章將教你如何使用 Struts 2 的應(yīng)用程序發(fā)送電子郵件。為了這個(gè)練習(xí),你需要從 JavaMail API 1.4.4 下載并安裝 mail.jar,并將 mail.jar 文件放置在你的 WEB-INF\lib 文件夾下,然后繼續(xù)按照創(chuàng)建動(dòng)作,視圖和配置文件的標(biāo)準(zhǔn)步驟進(jìn)行。

創(chuàng)建動(dòng)作

下一步是創(chuàng)建一個(gè)發(fā)送電子郵件的動(dòng)作方法。讓我們創(chuàng)建一個(gè)新類,稱為 Emailer.java,它的內(nèi)容如下。

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 有對(duì)應(yīng)于下面給出的email.jsp頁(yè)面中的表單屬性的屬性。這些屬性是:

  • from - 發(fā)件人的電子郵件地址。由于我們使用的是谷歌的 SMTP,因此我們需要一個(gè)有效的 gtalk id。
  • password - 上述帳戶的密碼
  • to - 給誰(shuí)發(fā)送電子郵件?
  • Subject - 電子郵件的主題
  • body - 實(shí)際的電子郵件消息

我們有沒有考慮過(guò)上述屬性的任何驗(yàn)證,驗(yàn)證將會(huì)在下一章中添加?,F(xiàn)在讓我們看看 execute() 方法。execute() 方法通過(guò)使用提供的參數(shù)用 javax 郵件庫(kù)發(fā)送一封電子郵件。如果郵件發(fā)送成功,動(dòng)作返回 SUCCESS,否則它返回 ERROR。

創(chuàng)建主頁(yè)面

讓我們編寫主頁(yè) JSP 文件 index.jsp,它將被用來(lái)收集電子郵件中上面提到的相關(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)建視圖

我們將使用 JSP 文件 success.jsp,假如動(dòng)作返回 SUCCESS,它將被調(diào)用,但假如動(dòng)作返回 ERROR,我們將有另一個(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>

下面將是一個(gè)視圖文件 error.jsp,假如動(dòng)作返回 ERROR。

<%@ 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 配置文件把一切都綜合起來(lá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="com.tutorialspoint.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)目名稱上點(diǎn)擊右鍵,并且單擊 Export > WAR File 來(lái)創(chuàng)建一個(gè) War 文件。然后在 Tomcat 的 webapps 目錄下部署這個(gè) WAR。最后,啟動(dòng) Tomcat 服務(wù)器和嘗試訪問(wèn) URL http://localhost:8080/HelloWorldStruts2/index.jsp. 將會(huì)給出下面的畫面:

http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts12.jpg" alt="" />

輸入所需的信息,并單擊 Send Email 按鈕。如果一切正常,那么你應(yīng)該看到下面的頁(yè)面:

http://wiki.jikexueyuan.com/project/struts-2/images/helloworldstruts13.jpg" alt="" />

上一篇:Spring 集成下一篇:類型轉(zhuǎn)換