トップ ライブラリ/Framework/CMS Struts Struts2

Apache Struts2とは―JavaのWebアプリフレームワークの入門知識。

Apache Struts2は、Strutsの次世代バージョンで、Javaプラットフォームを対象としてオープンソースのWebアプリケーション・フレームワークです。この記事ではStruts2の入門知識をまとめています。

▲記事トップへ

目次

この記事の目次です。

1. Struts2とは
2. 入門編
3. アノテーション
4. プロパティファイル
5. Strutsタグ

関連記事
更新履歴

1. Struts2とは

Apache Struts2は、Strutsの次世代バージョンで、Javaプラットフォームを対象としてオープンソースのWebアプリケーション・フレームワークです。

Struts2を使用してみて、たとえば、以下のような利点が感じられます。

2. 入門編

まずは簡単なHello Worldアプリケーションのサンプルコードを見ていきます。

動作環境

以下の環境で動作確認をおこないました。

アプリの構成

<tomcatホームディレクトリ>/webappsの下に以下の構成を作成します。

□Tomcatホーム/webapps/
├─conf
│      server.xml
└─webapps
    └─SampleStruts
        │  index.jsp
        └─WEB-INF
            │  web.xml
            ├─classes
            │  │  struts.xml
            │  └─sample
            │      └─struts
            │              IndexAction.class
            └─lib
                    commons-fileupload-1.2.2.jar
                    commons-io-2.0.1.jar
                    commons-lang3-3.1.jar
                    freemarker-2.3.19.jar
                    javassist-3.11.0.GA.jar
                    ognl-3.0.6.jar
                    struts2-codebehind-plugin-2.3.14.jar
                    struts2-core-2.3.14.jar
                    xwork-core-2.3.14.jar

関連ライブラリ(lib下に置くjarファイル)

Apache Strutsより、struts-2.3.14-all.zipをダウンロード・解凍し、 libフォルダにある以下のjarファイルを<Tomcatホーム>\webapps\SampleStruts\WEB-INF\libに配置します。

ソースコード

ページ(index.jsp)

<%@ page language="java" contentType="text/html;
     charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>サンプル</title></head>
<body>
ボタンを押すとメッセージが下に表示されます。
<s:form action="index.action"><s:submit value="ボタン"/></s:form>
<s:property value="message"/>
</body>
</html>

アクションクラス(IndexAction.java)

package sample.struts;
public class IndexAction {
  public String message;
  public String execute() {
    message = "Hello World!!";
    return "success";
  }
}

Strutsの設定ファイル(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.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="false" />
</struts>

アプリケーションの配備記述子(web.xml)

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>sample.struts</param-value>
</init-param>
</filter>

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

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

Tomcatの設定ファイル(server.xml)

<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
                     :
                  <省略>
                     :
  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
                     :
                  <省略>
                     :
    <Engine name="Catalina" defaultHost="localhost">
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
                     :
                  <省略>
                     :
        <Context path="/SampleStruts" docBase="<Webアプリケーションの置き場所>" />
                     :
                  <省略>
                     :
      </Host>
    </Engine>
  </Service>
</Server>

動作確認

Tomcatを起動し、ブラウザより「http://localhost:8080/SampleStruts/」へアクセスすると 「ボタン」が表示されます。そして、「ボタン」を押すと「ボタン」の下に「Hello World!!」と表示されます。

3. アノテーション

Struts2のアノテーションについて見ていきます。

Resultアノテーション(ページ遷移先を指定するサンプル)-Apache Struts2

Struts2のResultアノテーション(ページ遷移先を指定するサンプル)を見ていきます。

Welcomeページ(index.jsp)へ遷移し、ボタンを押すとHelloページ(hello.jsp)へ遷移するサンプルを紹介しています。

動作環境

以下の環境で動作確認をおこないました。

アプリの構成

<tomcatホームディレクトリ>/webappsの下に以下の構成を作成します。

□Tomcatホーム/webapps/
├─conf
│      server.xml
└─webapps
    └─SampleStruts
        │  index.jsp
        └─WEB-INF
            │  web.xml
            ├─classes
            │  │  struts.xml
            │  └─sample
            │      └─struts
            │              IndexAction.class
            ├─jsp
            │      hello.jsp
            └─lib
                    commons-fileupload-1.2.2.jar
                    commons-io-2.0.1.jar
                    commons-lang3-3.1.jar
                    freemarker-2.3.19.jar
                    javassist-3.11.0.GA.jar
                    ognl-3.0.6.jar
                    struts2-codebehind-plugin-2.3.14.jar
                    struts2-core-2.3.14.jar
                    xwork-core-2.3.14.jar

関連ライブラリ(lib下に置くjarファイル)

Apache Strutsより、struts-2.3.14-all.zipをダウンロード・解凍し、 libフォルダにある以下のjarファイルを<Tomcatホーム/webapps>/SampleStruts/webapps/SampleStruts/WEB-INF/libに配置します。

ソースコード

ページ(index.jsp)
<%@ page language="java" contentType="text/html;
     charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Welcomeページ</title></head>
<body>
ボタンを押すとhelloページに遷移します。
<s:form action="index.action">
<s:submit method="hello" value="ボタン"/>
</s:form>
</body>
</html>
アクションクラス(IndexAction.java)
package sample.struts;
import org.apache.struts2.config.Result;

@Result(name = "hello", value = "/WEB-INF/jsp/hello.jsp")
public class IndexAction {
  public String message;
  public String execute() {
    return "success";
  }
  public String hello() {
    message = "Hello World!!";
    return "hello";
  }
}

※本ソースのコンパイルには、以下のjarファイルが必要です。

ページ(hello.jsp)
<%@ page language="java" contentType="text/html;
     charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Helloページ</title></head>
<body>
<s:property value="message"/>
</body>
</html>

Strutsの設定ファイル(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.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="false" />
</struts>

アプリケーションの配備記述子(web.xml)

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>sample.struts</param-value>
</init-param>
</filter>

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

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

Tomcatの設定ファイル(server.xml)

<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
                     :
                  <省略>
                     :
  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
                     :
                  <省略>
                     :
    <Engine name="Catalina" defaultHost="localhost">
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
                     :
                  <省略>
                     :
        <Context path="/SampleStruts" reloadable="true" />
                     :
                  <省略>
                     :
      </Host>
    </Engine>
  </Service>
</Server>

動作確認

Tomcatを起動し、ブラウザより「http://localhost:8080/SampleStruts/」へアクセスすると Welcomeページが表示されます。

そして、「ボタン」を押すとHelloページに遷移し、「Hello World!!」と表示されます。

4. プロパティファイル

Struts2のプロパティファイルについて見ていきます。

プロパティファイルの設定と取得(作成したmessage_ja.propertiesからメッセージを取得するサンプル)-Struts2

Struts2のプロパティファイルの設定と取得(作成したmessage_ja.propertiesからメッセージを取得するサンプル)を見ていきます。

Welcomeページ(index.jsp)へ遷移し、ボタンを押すと作成したmessage_ja.propertiesから取得したメッセージが画面に表示されるサンプルを掲載しています。

動作環境

以下の環境で動作確認をおこないました。

アプリの構成

<tomcatホームディレクトリ>/webappsの下に以下の構成を作成します。

□Tomcatホーム/webapps/
├─conf
│      server.xml
└─webapps
    └─SampleStruts
        │  index.jsp
        └─WEB-INF
            │  web.xml
            ├─classes
            │  │  message_ja.properties
            │  │  struts.xml
            │  └─sample
            │      └─struts
            │              IndexAction.class
            └─lib
                    commons-fileupload-1.2.2.jar
                    commons-io-2.0.1.jar
                    commons-lang3-3.1.jar
                    freemarker-2.3.19.jar
                    javassist-3.11.0.GA.jar
                    ognl-3.0.6.jar
                    struts2-codebehind-plugin-2.3.14.jar
                    struts2-core-2.3.14.jar
                    xwork-core-2.3.14.jar

関連ライブラリ(lib下に置くjarファイル)

Apache Strutsより、struts-2.3.14-all.zipをダウンロード・解凍し、 libフォルダにある以下のjarファイルを<Tomcatホーム/webapps>/SampleStruts/webapps/SampleStruts/WEB-INF/libに配置します。

ソースコード

ページ(index.jsp)
<%@ page language="java"
            contentType="text/html; charset=UTF-8"
            pageEncoding="UTF-8"%>
<%@ 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>
<meta http-equiv="Content-Type"
         content="text/html; charset=UTF-8">
<title>サンプル</title>
</head>
<body>
<p>
<s:form action="index.action" theme="simple">
<s:submit value="データ取得"/>
</s:form>
</p>
<p>
<s:property value="label"/>
</p>
</body>
</html>
アクションクラス(IndexAction.java)
package sample.struts;
import com.opensymphony.xwork2.ActionSupport;
public class IndexAction extends ActionSupport {
  private static final long serialVersionUID = 1L;
  public String label;
  public String execute() {
    String embeddings[] = {"こんにちは", "太郎"};
    label = getText("MSG01",embeddings);
    return "success";
  }
}

※本ソースのコンパイルには、以下のjarファイルが必要です。

プロパティファイル(message_ja.properties)
MSG01={0}!{1}さん!
Strutsの設定ファイル(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.enable.DynamicMethodInvocation" value="true" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="message" />
</struts>

アプリケーションの配備記述子(web.xml)

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>sample.struts</param-value>
</init-param>
</filter>

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

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

Tomcatの設定ファイル(server.xml)

<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
                     :
                  <省略>
                     :
  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
                     :
                  <省略>
                     :
    <Engine name="Catalina" defaultHost="localhost">
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
                     :
                  <省略>
                     :
        <Context path="/SampleStruts" reloadable="true" />
                     :
                  <省略>
                     :
      </Host>
    </Engine>
  </Service>
</Server>

動作確認

Tomcatを起動し、ブラウザより「http://localhost:8080/SampleStruts/」へアクセスするとWelcomeページが表示されます。

そして、「ボタン」を「こんにちは!太郎さん! 」と表示されます。

5. Strutsタグ

Struts2のStrutsタグについて見ていきます。

actionerrorタグ(ログインフォームサンプル)-Struts2

Struts2のactionerrorタグ(ログインフォームサンプル)について見ていきます。

ログインフォームにメールアドレスとパスワードを入力し、不正入力の場合にログインフォーム上部にエラーメッセージが表示されるサンプルを掲載しています。

動作環境

以下の環境で動作確認をおこないました。

アプリの構成

<tomcatホームディレクトリ>/webappsの下に以下の構成を作成します。

□Tomcatホーム/webapps/
├─conf
│      server.xml
└─webapps
    └─SampleStruts
        │  index.jsp
        └─WEB-INF
            │  web.xml
            ├─classes
            │  │  struts.xml
            │  └─sample
            │      └─struts
            │              LoginAction.class
            ├─jsp
            │      hello.jsp
            └─lib
                    commons-fileupload-1.2.2.jar
                    commons-io-2.0.1.jar
                    commons-lang3-3.1.jar
                    freemarker-2.3.19.jar
                    javassist-3.11.0.GA.jar
                    ognl-3.0.6.jar
                    struts2-codebehind-plugin-2.3.14.jar
                    struts2-core-2.3.14.jar
                    xwork-core-2.3.14.jar

関連ライブラリ(lib下に置くjarファイル)

Apache Strutsより、struts-2.3.14-all.zipをダウンロード・解凍し、 libフォルダにある以下のjarファイルを<Tomcatホーム/webapps>/SampleStruts/webapps/SampleStruts/WEB-INF/libに配置します。

ソースコード

ページ(index.jsp)
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>ログインページ</title>
</head>
<body>
<s:actionerror />
<s:form action="login.action">
<s:textfield label="メールアドレス" name="email"/>
<s:password label="パスワード" name="pass" />
<s:submit/>
</s:form>
</body>
</html>
アクションクラス(LoginAction.java)
package sample.struts;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import com.opensymphony.xwork2.ActionSupport;

@Results({
 @Result(name="input",value="login.jsp"),
 @Result(name="success",value="/WEB-INF/jsp/hello.jsp")
})
public class LoginAction extends ActionSupport {
  private static final long serialVersionUID = 1L;
  public String email;
  public String pass;
  public String execute() {
    // 未入力チェック
    if (email == null || email.length() == 0) {
      addActionError("メールアドレスを入力してください。");
    }
    if (pass == null || pass.length() == 0) {
      addActionError("パスワードを入力してください。");
    }
    if (hasActionErrors()) {
      return "input";
    }
    // 入力内容チェック
    if (!(email.equals("e@ma.il") && pass.equals("pass"))) {
      addActionError("入力内容が不正です。");
    }
    if (hasActionErrors()) {
      return "input";
    }
    // エラーが無ければ成功
    return "success";
  }
}

※本ソースのコンパイルには、以下のjarファイルが必要です。

ページ(hello.jsp)
<%@ page language="java"
         contentType="text/html;charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Helloページ</title></head>
<body>
ようこそ!<s:property value="email"/>さん!
</body>
</html>

Strutsの設定ファイル(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.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="false" />
</struts>

アプリケーションの配備記述子(web.xml)

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>sample.struts</param-value>
</init-param>
</filter>

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

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

Tomcatの設定ファイル(server.xml)

<?xml version='1.0' encoding='utf-8'?>
<Server port="8005" shutdown="SHUTDOWN">
                     :
                  <省略>
                     :
  <Service name="Catalina">
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
                     :
                  <省略>
                     :
    <Engine name="Catalina" defaultHost="localhost">
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
                     :
                  <省略>
                     :
        <Context path="/SampleStruts" reloadable="true" />
                     :
                  <省略>
                     :
      </Host>
    </Engine>
  </Service>
</Server>

動作確認

Tomcatを起動し、ブラウザより「http://localhost:8080/SampleStruts/」へアクセスすると ログインページが表示されます。

そして、フォームにメールアドレスとパスワードを入力し、「ボタン」を押すとHelloページに遷移し、「ようこそ!<メールアドレス>さん!」と表示されます。

ただし、メールアドレスまたはパスワードが不正の場合、ログインページのフォーム上部にエラーメッセージが表示されます。

もっと知識を広げるための参考

もっと知識を広げるための参考です。

Struts

StrutsをテーマにStrutsとはの概要、Struts1とは何か、Struts2とは何かをまとめています。

詳細

更新履歴

この記事の更新履歴です。

戻る

スポンサーリンク

サイト内のページ

言語
C・C++ /HTML /Java /JavaScript /PHP /シェルスクリプト

開発環境
Ant /Burp /Eclipse /Fiddler /gcc /gdb /Git /g++ /JDK /JMeter /JUnit /Teraterm /ZAP

技術・仕様
Ajax /CORBA /Jakarta EE(旧称J2EE、Java EE) /JNI

ライブラリ/Framework/CMS
bootstrap /jQuery /FuelPHP /Lucene /MyBatis /Seasar2 /Spring /Struts /WordPress

Web API
Google Maps

ITインフラOSとミドルウェア
Linux /Windows /シェル
ActiveMQ /Tomcat /MariaDB /MySQL /Nagios /Redis /Solr

ITインフラサーバー
公開Webサーバー

ITインフラネットワーク
プログラミング /構築

ITインフラセキュリティ
公開サーバーのセキュリティ

PC製品
ZOTAC

SI
ホームページの作り方

その他
IT用語 /ITスキル体系

スポンサーリンク

関連サイト内検索ツール

zealseedsおよび関連サイト内のページが検索できます。

IPアドレス確認ツール

あなたのグローバルIPアドレスは以下です。

3.138.114.94

HTMLの表示色確認ツール

パスワード生成ツール

文字数のプルダウンを選択して、取得ボタンを押すと「a~z、A~Z、0~9」の文字を ランダムに組み合わせた文字列が表示されます。

ここに生成されます。

スポンサーリンク