Struts-2-struts-sending-email

提供:Dev Guides
移動先:案内検索

Struts 2-メールの送信

この章では、Struts 2アプリケーションを使用して電子メールを送信する方法について説明します。

この演習では、https://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-eeplat-419426l#javamail-1.4.4-othからmail.jarをダウンロードしてインストールする必要があります。 -JPR [JavaMail API 1.4.4]および mail.jar ファイルをWEB-INF \ libフォルダーに配置し、アクション、ビュー、および構成ファイルを作成する標準の手順に従います。

アクションを作成

次のステップは、電子メールの送信を処理するActionメソッドを作成することです。 次の内容を持つ Emailer.java という新しいクラスを作成しましょう。

package com.finddevguides.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 -送信者の電子メールアドレス。 GoogleのSMTPを使用しているため、有効なgtalk IDが必要です
  • パスワード-上記のアカウントのパスワード
  • To -メールの送信先
  • 件名-メールの件名
  • Body -実際の電子メールメッセージ

上記のフィールドの検証については検討していませんが、次の章で検証を追加します。 ここで、execute()メソッドを見てみましょう。 execute()メソッドはjavax Mailライブラリを使用して、指定されたパラメーターを使用して電子メールを送信します。 メールが正常に送信された場合、アクションはSUCCESSを返し、そうでない場合はERRORを返します。

メインページを作成

上記の電子メール関連情報を収集するために使用されるメインページJSPファイル index.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 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>

ビューを作成する

アクションがSUCCESSを返した場合に呼び出されるJSPファイル success.jsp を使用しますが、アクションから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 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.finddevguides.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 にアクセスしてみます。 これにより、次の画面が生成されます-

ユーザー入力のメール送信

必要な情報を入力し、[メールを送信]ボタンをクリックします。 すべてがうまくいくと、次のページが表示されます。

メール成功