TOPページへ戻る

Struts 7.0.0のインストールとサンプル Part2

ここでは、Javaでウェブアプリケーションの作成が行えるStruts 7.0.0のインストールとサンプルアプリケーションの作成と実行を行います。
    ※JDK、EclipseのインストールのページでEclipseがインストールされていることを前提にしています。
    ※Struts 7.0.0のインストールとサンプルのページを参照し、ある程度の知識があることを前提にしています。

EclipseでStruts2

Struts2は初期状態でインストールされていないためStrutsのサイトからダウンロードしインストールする必要がある。

Struts2 サンプル作成2

Struts 7.0.0のサンプルを作成する

ポイント

フォームの処理、フォーム検証、メッセージリソース(国際化、日本語)のサンプルです。

ソースコードをzipファイルにしました。こちらもご利用ください。
  1. Downloadsにzipファイルをダウンロードし、そこでzipを7-Zipで解凍する。
    Strutsのサイトにアクセスし、以下のファイルをダウンロード
    https://struts.apache.org/download.cgi
    ダウンロードするファイル struts-7.0.0-all.zip
    ダウンロードするフォルダはデフォルト。(エクスプローラのDownloadsフォルダ)

    解凍するファイル
    C:\Users\(ユーザ名)\Downloads\struts-7.0.0-all.zip
    解凍するとできるフォルダ
    C:\Users\(ユーザ名)\Downloads\struts-7.0.0-all\struts-7.0.0

    さらにwarファイルを7-Zipで解凍する
    解凍するファイル
    C:\Users\(ユーザ名)\Downloads\struts-7.0.0-all\struts-7.0.0\apps\struts2-rest-showcase-7.0.0.war
    解凍するとできるフォルダ
    C:\Users\(ユーザ名)\Downloads\struts-7.0.0-all\struts-7.0.0\apps\struts2-rest-showcase-7.0.0

  2. プロジェクトの作成
    新規アイコン→Web→動的Webプロジェクト
    プロジェクト名 test3と入力
    ターゲット・ランタイムをTomcat10(Java17)かTomcat10(Java21)にする。

  3. エクスプローラでコピー元のフォルダのlibフォルダをコピー先へコピー
    strutsのjarファイルをコピー
    コピー元
    C:\Users\(ユーザ名)\Downloads\struts-7.0.0-all\struts-7.0.0\apps\struts2-rest-showcase-7.0.0\WEB-INF\lib\*
    コピー先
    C:\pleiades\2024-12\workspace\(プロジェクト名)\src\main\webapp\WEB-INF\lib
    (重要)コピー先から以下のjarファイルを削除
    struts2-rest-plugin-7.0.0.jar


  4. javaソースファイル、JSPファイル、XML、propertiesファイルの作成
    1)Javaソースの作成
    MessageStore.javaの作成
    クラスの作成
    (プロジェクト名)\src\main\javaフォルダをクリックし以下を実行
    新規アイコン→Java→クラス
    パッケージにtest3.sample.modelを入力
    名前にMessageStoreを入力、完了をクリック。

    以下のサンプルソースを作成
    MessageStore.java
    package test3.sample.model;

    public class MessageStore {

      private String message;

      public MessageStore() {
        setMessage("Hello Struts User");
      }

      public String getMessage() {
        return message;
      }

      public void setMessage(String message) {
        this.message = message;
      }

      public String toString() {
        return message + " (from toString)";
      }

    }

    同様に以下のサンプルソースを作成
    Person.java
    package test3.sample.model;

    public class Person
    {
        private String firstName;
        private String lastName;
        private String email;
        private int age;

        public String getFirstName()
        {
            return firstName;
        }

        public void setFirstName(String firstName)
        {
            this.firstName = firstName;
        }

        public String getLastName()
        {
            return lastName;
        }

        public void setLastName(String lastName)
        {
            this.lastName = lastName;
        }

        public String getEmail()
        {
            return email;
        }

        public void setEmail(String email)
        {
            this.email = email;
        }

        public int getAge()
        {
            return age;
        }

        public void setAge( int age)
        {
            this.age = age;
        }

        public String toString()
        {
            return "First Name: " + getFirstName() + " Last Name:  " + getLastName() +
            " Email:      " + getEmail() + " Age:      " + getAge() ;
        }
    }

    HelloWorldAction.javaの作成
    クラスの作成
    (プロジェクト名)\src\main\javaフォルダをクリックし以下を実行
    新規アイコン→Java→クラス
    パッケージにtest3.sample.actionを入力
    名前にHelloWorldActionを入力、完了をクリック。

    以下のサンプルソースを作成
    HelloWorldAction.java
    package test3.sample.action;

    import org.apache.struts2.ActionSupport;
    import org.apache.struts2.interceptor.parameter.StrutsParameter;

    import test3.sample.model.MessageStore;

    public class HelloWorldAction extends ActionSupport {

      private static final long serialVersionUID = 1L;

      private MessageStore messageStore;

      private static int helloCount = 0;

      public int getHelloCount() {
        return helloCount;
      }

      public void setHelloCount(int helloCount) {
        HelloWorldAction.helloCount = helloCount;
      }

      private String userName;

      @StrutsParameter(depth = 1)
      public String getUserName() {
        return userName;
      }

      @StrutsParameter(depth = 1)
      public void setUserName(String userName) {
        this.userName = userName;
      }

      public String execute() throws Exception {

        messageStore = new MessageStore() ;

        //Action included a query string parameter of userName
        //or a form field with name of userName
        if (userName != null) {

          messageStore.setMessage( messageStore.getMessage() + " " + userName);

        }

        helloCount++;

        return SUCCESS;
      }

      @StrutsParameter(depth = 1)
      public MessageStore getMessageStore() {
        return messageStore;
      }

      @StrutsParameter(depth = 1)
      public void setMessageStore(MessageStore messageStore) {
        this.messageStore = messageStore;
      }

    }

    同様に以下のサンプルソースを作成
    Register.java
    package test3.sample.action;

    import test3.sample.model.Person;

    import org.apache.struts2.ActionSupport;
    import org.apache.struts2.interceptor.parameter.StrutsParameter;

    public class Register extends ActionSupport {

      private static final long serialVersionUID = 1L;

      private Person personBean;

      public String execute() throws Exception {

        return SUCCESS;

      }

      public void validate(){

        if ( personBean.getFirstName().length() == 0 ){  
          //addFieldError( "personBean.firstName", "First name is required." );
          addFieldError( "personBean.firstName", getText("personBean.firstName_missing") );
        }

        if ( personBean.getEmail().length() == 0 ){  
          //addFieldError( "personBean.email", "Email is required." );
          addFieldError( "personBean.email", getText("personBean.email_missing" ) );
        }

        if ( personBean.getAge() < 18 )
        {  
          //addFieldError( "personBean.age", "Age is required and must be 18 or older" );
          addFieldError( "personBean.age", getText("personBean.age_missing") );
        }

      }

      @StrutsParameter(depth = 1)
      public Person getPersonBean() {

        return personBean;

      }

      @StrutsParameter(depth = 1)
      public void setPersonBean(Person person) {

        personBean = person;

      }

    }

    2)JSPファイルの作成
    (プロジェクト名)\webapp直下に作成
    webappフォルダをクリックし以下を実行
    新規アイコン→Web→JSPファイル
    ファイル名にindex.jspと入力。
    新規JSPファイル(html5)を選択し、完了をクリック。

    以下のサンプルソースを作成
    index.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html>
    <html charset="UTF-8">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Basic Struts 2 Application - Welcome</title>
    </head>
    <body>
    <h1>Welcome to Struts 2</h1>

    <p><a href="<s:url namespace='' action='hello'/>">Hello World</a></p>
    <s:url namespace='' action="hello" var="helloLink">
    <s:param name="userName">Bruce Phillips</s:param>
    </s:url>
    <p><a href="${helloLink}">Hello Bruce Phillips</a></p>

    <p>Get your own personal hello by filling out and submitting this form.</p>

    <s:form namespace='' action="hello">

    <s:textfield name="userName" label="Your name" />

    <s:submit value="Submit" />

    </s:form>

    <s:url namespace='' action="registerInput" var="registerInputLink" >
    <s:param name="request_locale">en</s:param>
    </s:url>
    <p><a namespace='' href="${registerInputLink}">Please register</a> for our prize drawing.</p>

    <h3>登録 日本語</h3>
    <s:url namespace='' action="registerInput" var="registerInputLinkJA">
    <s:param name="request_locale">ja</s:param>
    </s:url>
    <p>賞を授与するため<a href="${registerInputLinkJA}">登録してください</a></p>
    <%--
    --%>
    <hr />
    <s:text name="contact" />
    <%--
    <br>
    <s:i18n name="global">
    <s:text name="contact" />
    </s:i18n>
    <br>
    <s:i18n name="global_en">
    <s:text name="contact" />
    </s:i18n>
    --%>
    </body>
    </html>

    同様に、以下のサンプルソースを作成
    HelloWorld.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html>
    <html charset="UTF-8">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Hello World!</title>
    </head>
    <body>
    <h1><s:text name="greeting" /></h1>
    <h2><s:property value="messageStore.message" /></h2>
    <p>I've said hello <s:property value="helloCount" /> times!</p>
    <p><s:property value="messageStore" /></p>
    <p><a href="<s:url action='index' />" >Return to home page</a>.</p>
    <hr />
    <s:text name="contact" />
    </body>
    </html>

    同様に、以下のサンプルソースを作成
    register.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html>
    <html charset="UTF-8">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Register</title>
    <s:head />
    </head>
    <body>
    <h1><s:text name="greeting" /></h1>
    <h3><s:text name="instructions" /></h3>

    <s:form action="registerExec">

    <s:textfield key="personBean.firstName" />
    <s:textfield key="personBean.lastName" />
    <s:textfield key="personBean.email" />
    <s:textfield key="personBean.age" />

    <s:submit key="submit" />

    </s:form>
    <hr />
    <s:text name="contact" />
    </body>
    </html>

    同様に、以下のサンプルソースを作成
    thankyou.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html>
    <html charset="UTF-8">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Registration Successful</title>
    </head>
    <body>
    <h3><s:text name="thankyou" /></h3>

    <p>Your registration information: <s:property value="personBean" /> </p>

    <p><a href="<s:url action='index' />" >Return to home page</a>.</p>
    <hr />
    <s:text name="contact" />
    </body>
    </html>

    3)XMLファイル
    struts.xmlファイル
    (プロジェクト名)\src\main\javaフォルダの下に作成
    ファイル名にstruts.xmlと入力し、完了をクリック。
    以下のXMLファイルを作成。
    struts.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
        "https://struts.apache.org/dtds/struts-2.5.dtd">

    <struts>

      <constant name="struts.devMode" value="true" />
      <constant name="struts.custom.i18n.resources" value="global" />
      <constant name="struts.allowlist.packageNames" value="test3.sample" />

      <package name="basicstruts2" extends="struts-default">

            <!-- If no class attribute is specified the framework will assume success and
            render the result index.jsp -->
            <!-- If no name value for the result node is specified the success value is the default -->
        <action name="index">
          <result>/index.jsp</result>
        </action>

        <!-- If the URL is hello.action then call the execute method of class HelloWorldAction.
        If the result returned by the execute method is success render the HelloWorld.jsp -->
        <action name="hello" class="test3.sample.action.HelloWorldAction" method="execute">
          <result name="success">/HelloWorld.jsp</result>
        </action>

         <action name="registerInput" class="test3.sample.action.Register" method="input" >
          <result name="input">/register.jsp</result>
        </action>

        <action name="registerExec" class="test3.sample.action.Register" method="execute">
        <result name="success">/thankyou.jsp</result>
        <result name="input">/register.jsp</result>
        </action>

      </package>

    </struts>

    log4j2.xmlファイル
    (プロジェクト名)\src\main\javaフォルダの下に作成
    同様に以下のXMLファイルを作成。
    log4j2.xmlファイル
    <?xml version="1.0" encoding="UTF-8"?>
    <!--
    /*
    * Licensed to the Apache Software Foundation (ASF) under one
    * or more contributor license agreements.  See the NOTICE file
    * distributed with this work for additional information
    * regarding copyright ownership.  The ASF licenses this file
    * to you under the Apache License, Version 2.0 (the
    * "License"); you may not use this file except in compliance
    * with the License.  You may obtain a copy of the License at
    *
    *  http://www.apache.org/licenses/LICENSE-2.0
    *
    * Unless required by applicable law or agreed to in writing,
    * software distributed under the License is distributed on an
    * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    * KIND, either express or implied.  See the License for the
    * specific language governing permissions and limitations
    * under the License.
    */
    -->
    <Configuration>
        <Appenders>
            <Console name="STDOUT" target="SYSTEM_OUT">
                <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
            </Console>
        </Appenders>
        <Loggers>
            <Logger name="org.apache.struts2" level="info"/>
            <Logger name="test3" level="debug"/>
            <Root level="warn">
                <AppenderRef ref="STDOUT"/>
            </Root>
        </Loggers>
    </Configuration>

    web.xmlファイル
    (プロジェクト名)\src\main\webapp\WEB-INFフォルダの下に作成
    以下のXMLファイルを編集。
    web.xmlファイル
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app>

      <display-name>test3</display-name>
      <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
      </filter>

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

      <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.jsp</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>index</welcome-file>
      </welcome-file-list>

    </web-app>

    4)propertiesファイル
    global.properties
    (プロジェクト名)\src\main\javaフォルダをクリックし以下を実行
    新規アイコン→一般→ファイル
    名前にglobal.propertiesを入力、完了をクリック。
    contact=For assistance contact <a href='mailto:contact@email.com'>contact@email.com</a>

    global_en.properties
    同様に以下のサンプルソースを作成
    (プロジェクト名)\src\main\javaフォルダにファイルを作成する。
    contact=For assistance contact <a href='mailto:contact@email.com'>contact@email.com</a>

    global_ja.properties
    (プロジェクト名)\src\main\javaフォルダにファイルを作成する。
    日本語で記述するpropertiesファイルは、以下の手順で作成する。

    1. 新規アイコン→一般→ファイル
      global_ja.propertiesファイルを作成する
    2. Eclipse のプロジェクト・エクスプローラーから、global_ja.propertiesを右クリック

    3. プロパティーをクリック
    4. リソース→テキスト・ファイル・エンコード→その他:ISO-8859-1 を選択

    5. 適用して閉じる、をクリック
    6. Eclipse のプロジェクト・エクスプローラーから、global_ja.propertiesを右クリック→次で開く
    7. Limy プロパティー・エディター(native2ascii)をクリック

    8. ファイルの中身を記述する


    9. 保存

    global_ja.propertiesファイルの内容
    contact=アシストを希望するにはコンタクトして下さい<a href='mailto:contact@email.com'>contact@email.com</a>

    備考

    package.properties
    (プロジェクト名)\src\main\java\test3\sampleフォルダにファイルを作成する。
    greeting=Welcome to The Wonderful World of Struts 2
    instructions=Register for a prize by completing this form.

    package_en.properties
    (プロジェクト名)\src\main\java\test3\sampleフォルダにファイルを作成する。
    greeting=Welcome to The Wonderful World of Struts 2
    instructions=Register for a prize by completing this form.

    package_ja.properties
    (プロジェクト名)\src\main\java\test3\sampleフォルダにファイルを作成する。
    global_ja.propertiesファイルを作成したのと同様の手順で作成する。
    greeting=ようこそStrutsの素晴らしい世界へ
    instructions=賞を授与するためこのフォームを登録

    Register.properties
    (プロジェクト名)\src\main\java\test3\sample\actionフォルダにファイルを作成する。
    personBean.firstName=First name
    personBean.firstName_missing=First name is required.
    personBean.lastName=Last name
    personBean.age=Age
    personBean.age_missing=Age is required and must be 18 or older
    personBean.email=Email
    personBean.email_missing=Email is required.
    thankyou=Thank you for registering %{personBean.firstName}.
    submit=Register

    Register_en.properties
    (プロジェクト名)\src\main\java\test3\sample\actionフォルダにファイルを作成する。
    personBean.firstName=First name
    personBean.firstName_missing=First name is required.
    personBean.lastName=Last name
    personBean.age=Age
    personBean.age_missing=Age is required and must be 18 or older
    personBean.email=Email
    personBean.email_missing=Email is required.
    thankyou=Thank you for registering %{personBean.firstName}.
    submit=Register

    Register_ja.properties
    (プロジェクト名)\src\main\java\test3\sample\actionフォルダにファイルを作成する。
    global_ja.propertiesファイルを作成したのと同様の手順で作成する。
    personBean.firstName=名
    personBean.firstName_missing=名は必須入力です
    personBean.lastName=姓
    personBean.age=年齢
    personBean.age_missing=年齢は必須入力です。18歳以上である必要があります
    personBean.email=Eメール
    personBean.email_missing=Eメールは必須入力です
    thankyou=登録ありがとうございます。 %{personBean.firstName}さん
    submit=登録

    6)最後に以下のようなフォルダ構成となっているか確認します。


  5. ビルドが終了したら、プロジェクトのトップにマウスカーソルを移動、実行ボタンをクリックしTomcatを起動する
    以下にブラウザでアクセス(自動でブラウザが起動しアクセスする)
    http://localhost:8080/test3/

    実行結果



    サンプルを終了させたい場合、サーバービューでサーバーを停止ボタンをクリックしTomcatを終了させます

  6. プロジェクトが必要なくなったら、閉じておきます。
    Serversのプロジェクトは、Tomcatのことなので閉じてはいけません。

参考1 getter/setterについて

modelで、setメソッドやgetメソッド(getter/setter)を作成する場合、Eclipseに簡単に作成する機能があります。
  1. 変数を定義する

  2. 右クリックで「ソース」の「getterおよびsetterの生成」をクリック

  3. 作成するgetterおよびsetterを選択し、「生成」ボタンをクリック
    このとき「メソッド・コメントの生成」をチェックしておくと、コメントも合わせて生成されます。

  4. 実行例

参考2

Javadoc(API)やチュートリアルなど参考URLを紹介します
以上