TOPページへ戻る

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

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

EclipseでStruts2

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

Struts2 サンプル作成3

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プロジェクト
    プロジェクト名 test4と入力
    ターゲット・ランタイムを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ファイルの作成
    1)Javaソースの作成
    AuthenticationAction.javaの作成
    クラスの作成
    (プロジェクト名)\src\main\javaフォルダをクリックし以下を実行
    新規アイコン→Java→クラス
    パッケージにtest4.sample.actionを入力
    名前にAuthenticationActionを入力、完了をクリック。

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

    import java.util.Map;

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

    public class AuthenticationAction extends ActionSupport implements SessionAware {
        private Map<String, Object> sessionMap;
        private String userName;
        private String password;
        private boolean isAuthenticated = false;

        public String execute() throws Exception {
          return SUCCESS;
        }

        public String login() {
          String loggedUserName = null;

          // check if the userName is already stored in the session
          if (sessionMap.containsKey("userName")) {
            loggedUserName = (String) sessionMap.get("userName");
          }
          if (loggedUserName != null
              //&& loggedUserName.equals("admin")
            ) {
            //System.out.println("loggedUserName is not null");
            return SUCCESS;  // return welcome page
          }

          // if no userName stored in the session,
          // check the entered userName and password
          if (userName != null
              //&& userName.equals("admin")
              //&& password != null
              //&& password.equals("adminpasswd")
              && isAuthenticated) {
            
            // add userName to the session
            sessionMap.put("userName", userName);
            //System.out.println("isAuthenticated is true.userName(" + userName + ")");
            
            return SUCCESS;  // return welcome page
          }

          // in other cases, return login page
          return INPUT;
        }

         public void validate(){

            if ( userName != null && userName.length() == 0 ){
              addFieldError( "userName", "UserName is required." );
              isAuthenticated = false;
            }
            if ( password != null && password.length() == 0 ){  
                addFieldError( "password", "password is required." );
               isAuthenticated = false;
            }

            if (userName != null
                && userName.length() > 0
                && !(userName.equals("admin"))) {
              addFieldError( "password", "UserName or password is not correct." );
              isAuthenticated = false;
            }

            if (userName != null
                && userName.length() > 0
                && userName.equals("admin")
                && password != null
                && password.length() > 0
                && !(password.equals("adminpasswd"))) {
              addFieldError( "password", "UserName or password is not correct." );
               isAuthenticated = false;
            }
            else {
              isAuthenticated = true;
            }

         }

          public String logout() {
            // remove userName from the session
            if (sessionMap.containsKey("userName"))
            {
              sessionMap.remove("userName");
            }
            isAuthenticated = false;
            //System.out.println("isAuthenticated is " + isAuthenticated);
            return SUCCESS;
          }

      //   public void setSession(Map sessionMap) {
    //        this.sessionMap = sessionMap;
    //      }

          public void withSession(Map session) {
            sessionMap = session;
          }

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

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

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

    以下のサンプルソースを作成
    Login.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Struts2 Login</title>
    <s:head />
    </head>
    <body>
      <center>
        <h3>Login</h3>
        <s:form namespace='' action="login" method="post">
          <s:textfield name="userName" label="Enter User Name" />
          <s:password name="password" label="Enter Password" />
          <s:submit label="Login" />
        </s:form>
      </center>
    </body>
    </html>

    同様に、以下のサンプルソースを作成
    Welcome.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Welcome</title>
    </head>
    <body>
      <center>
    <h3>Welcome you have logged in successfully!</h3>
        <h3>Welcome <i>${sessionScope.userName}</i>, you have logged in successfully!</h3>
    <p>I've said hello to you <s:property value="#session.userName" /></p>
    <%--
    --%>
        <h3><a href="logout">Logout</a></h3>
      </center>
    </body>
    </html>

    3)XMLファイル
    struts.xmlファイル
    (プロジェクト名)\src\main\javaフォルダの下に作成
    ファイル名にstruts.xmlと入力し、完了をクリック。
    以下のXMLファイルを作成。
    struts.xml
    <!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" />
      <constant name="struts.allowlist.packageNames" value="test4.sample" />

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

        <action name="index" class="test4.sample.action.AuthenticationAction"
            method="execute">
          <result name="success">/Login.jsp</result>
          <result name="input">/Login.jsp</result>
        </action>
        
        <action name="login" class="test4.sample.action.AuthenticationAction"
            method="login">
          <result name="success">/Welcome.jsp</result>
          <result name="input">/Login.jsp</result>
        </action>

        <action name="logout" class="test4.sample.action.AuthenticationAction"
            method="logout">
          <result name="success">/Login.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="test4" 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>test4</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)htmlファイル
    (プロジェクト名)\src\main\webappフォルダをクリックし以下を実行
    新規アイコン→Web→HTMLファイル
    名前にindex.htmlを入力、完了をクリック。

    index.html
    <!DOCTYPE html>
    <html>
    <head>
        <META HTTP-EQUIV="Refresh" CONTENT="0;URL=index">
    </head>

    <body>
    <p>Loading ...</p>
    </body>
    </html>

  5. ビルドが終了したら、プロジェクトのトップにマウスカーソルを移動、実行ボタンをクリックしTomcatを起動する
    以下にブラウザでアクセス(自動でブラウザが起動しアクセスする)
    AuthenticationAction.javaのソースに記述されていますが、ユーザ名はadmin、パスワードはadminpassでログインできます。
    http://localhost:8080/test4/

    実行結果



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

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

参考1

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