TOPページへ戻る

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

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

EclipseでStruts2

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

PostgreSQL

このページを記述した時点の最新版は、PostgreSQL バージョン 17.4 である。

JDBCドライバとコネクションプーリング

JDBCドライバは、PostgreSQL本体のインストーラに同梱しているものを使用する。
コネクションプーリングの最新版は、Apache Commons DBCP 2.13.0である。

Struts2 サンプル作成6

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

ポイント

PostgreSQL連携のサンプルです。
JDBCドライバとコネクションプーリングを使用して、PostgreSQLにアクセスします。

ソースコードを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. Downloadsにコネクションプーリングのzipファイルをダウンロードし、そこでzipを7-Zipで解凍する。
    https://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi
    ダウンロードするファイル commons-dbcp2-2.13.0-bin.zip
    ダウンロードするフォルダはデフォルト。(エクスプローラのDownloadsフォルダ)

  3. DownloadsにPostgreSQLのインストーラをダウンロード、実行する。
    https://www.enterprisedb.com/downloads/postgres-postgresql-downloads
    ダウンロードするファイル postgresql-17.4-1-windows-x64.exe
    ダウンロードするフォルダはデフォルト。(エクスプローラのDownloadsフォルダ)
    以下のサイトを参考にインストールして下さい。
    https://qiita.com/tom-sato/items/037b8f8cb4b326710f71

    PostgreSQLの管理者(postgres)のパスワードは、忘れないようにして下さい。
    インストールの最後にStack Builderを起動させJDBCドライバをインストールします。
    (起動せずにインストールを終了させてしまった場合も、スタートメニューからStack Builderを起動させることができます。)
    カテゴリ→Database Drivers→pgJDBCv42.7.2-1をチェック、次へをクリックしインストールを完了させます。

    インストール後以下を行います。
    1)SQL Shell(psql)を起動し、ログインします。
    Server: localhost (デフォルト)
    Database: postgres (デフォルト)
    Port: 5432 (デフォルト)
    Username: postgres (デフォルト)
    Client Encoding: SJIS (デフォルト)
    ユーザ postgres のパスワード: (自分で設定したパスワード)



    2)ログインしたら以下のSQLを実行します。(コピー・右クリックで貼り付けでOKです。)
    -- ユーザ作成
    CREATE ROLE testuser WITH
      LOGIN
      NOSUPERUSER
      INHERIT
      NOCREATEDB
      NOCREATEROLE
      NOREPLICATION
      NOBYPASSRLS
      PASSWORD 'userpass';

    -- Database作成
    CREATE DATABASE mydb
        WITH
        OWNER = testuser
        ENCODING = 'UTF8'
        LC_COLLATE = 'C'
        LC_CTYPE = 'C'
        LOCALE_PROVIDER = 'libc'
        TABLESPACE = pg_default
        CONNECTION LIMIT = -1
        IS_TEMPLATE = False;

    3)引き続き、SQL Shell(psql)で、以下のように入力し、今作ったユーザ testuser でログインします。
    パスワードは、userpass です。

    \c mydb testuser  



    4)スキーマ、テーブルの作成を行います。
    以下のSQLを実行します。(コピー・右クリックで貼り付けでOKです。)
    -- スキーマ作成
    CREATE SCHEMA IF NOT EXISTS myschema AUTHORIZATION testuser;
    -- テーブル作成
    CREATE TABLE myschema.weather (
        city            varchar(80),   -- charcter varying型
        temp_lo         int,           -- 最低気温 integer型
        temp_hi         int,           -- 最高気温 integer型
        prcp            real,          -- 降水量 real型
        date            date           -- date型
    );
    -- データの作成
    INSERT INTO myschema.weather VALUES ('San Francisco', 46, 50, 0.25, '1994-11-27');
    INSERT INTO myschema.weather (city, temp_lo, temp_hi, prcp, date) VALUES ('San Francisco', 43, 57, 0.0, '1994-11-29');
    INSERT INTO myschema.weather (date, city, temp_hi, temp_lo) VALUES ('1994-11-29', 'Hayward', 54, 37);

    実行したら、\q を入力し終了します。


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

  5. エクスプローラでコピー元のフォルダの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


    JDBCドライバのjarファイル postgresql-42.7.2.jar をコピー
    コピー元
    C:\Program Files (x86)\PostgreSQL\pgJDBC
    コピー先
    C:\pleiades\2024-12\workspace\(プロジェクト名)\src\main\webapp\WEB-INF\lib

    コネクションプーリングのjarファイル commons-dbcp2-2.13.0.jar をコピー
    コピー元
    C:\Users\(ユーザ名)\Downloads\commons-dbcp2-2.13.0-bin\commons-dbcp2-2.13.0
    コピー先
    C:\pleiades\2024-12\workspace\(プロジェクト名)\src\main\webapp\WEB-INF\lib

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

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

    import java.math.BigDecimal;

    public class Weather {
        private String city;
        private Integer temp_lo;
        private Integer temp_hi;
        private BigDecimal prcp;
        private String date;

        public String getCity() {
            return city;
        }
        public void setCity(String city) {
            this.city = city;
        }
        public Integer getTemp_lo() {
            return temp_lo;
        }
        public void setTemp_lo(Integer temp_lo) {
            this.temp_lo = temp_lo;
        }
        public Integer getTemp_hi() {
            return temp_hi;
        }
        public void setTemp_hi(Integer temp_hi) {
            this.temp_hi = temp_hi;
        }
        public BigDecimal getPrcp() {
            return prcp;
        }
        public void setPrcp(BigDecimal prcp) {
            this.prcp = prcp;
        }
        public String getDate() {
            return date;
        }
        public void setDate(String date) {
            this.date = date;
        }

    }

    クラスの作成
    (プロジェクト名)\src\main\javaフォルダをクリックし以下を実行
    新規アイコン→Java→クラス
    パッケージにtest7.sample.daoを入力
    以下のサンプルソースを作成

    InitDataSource.java
    package test6.sample.dao;

    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.sql.DataSource;

    public class InitDataSource {
        private static Context context = null;
        private static DataSource ds = null;

        public static DataSource getInstance() throws Exception {
          if (context == null) {
            context = new InitialContext();
          }
          if (ds == null) {
            ds = (DataSource)context.lookup("java:comp/env/mydb");
          }
          return ds;
        }

    }

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

    以下のサンプルソースを作成
    WeatherDAO.java
    package test7.sample.dao;

    import java.math.BigDecimal;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.List;

    import javax.sql.DataSource;

    import test7.sample.model.Weather;

    public class WeatherDAO {
          DataSource ds;

          public WeatherDAO() throws Exception {
              ds = InitDataSource.getInstance();
          }

          public List<Object> selectWeather() throws Exception {

            PreparedStatement ps = null;
            ResultSet rs = null;
            List<Object> weatherList = new ArrayList<>();

            Connection conn = ds.getConnection();
            conn.setSchema("myschema");

    //        String SQL = "SELECT CITY, TEMP_LO, TEMP_HI, PRCP, DATE FROM MYSCHEMA.WEATHER";
            String SQL = "SELECT CITY, TEMP_LO, TEMP_HI, PRCP, DATE FROM WEATHER";

            try {
              ps = conn.prepareStatement(SQL);
              rs = ps.executeQuery();
              while(rs.next()){
                String city = rs.getString("city");
                Integer temp_lo = rs.getInt("temp_lo");
                Integer temp_hi = rs.getInt("temp_hi");
                BigDecimal prcp = rs.getBigDecimal("prcp");
                String date = rs.getDate("date").toString();

                Weather weather = new Weather();
                weather.setCity(city);
                weather.setTemp_lo(temp_lo);
                weather.setTemp_hi(temp_hi);
                weather.setPrcp(prcp);
                weather.setDate(date);

                weatherList.add(weather);
              }
            }
            finally {
              ps.close();
              rs.close();
              conn.close();
            }

            return weatherList;
          }
    }

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

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

    import java.util.ArrayList;
    import java.util.List;

    import org.apache.struts2.ActionSupport;

    import test7.sample.dao.WeatherDAO;

    public class WeatherListAction extends ActionSupport {
          private static final long serialVersionUID = 1L;

          private List<Object> weatherList = new ArrayList<>();

          public String execute() throws Exception {

            WeatherDAO dao = new WeatherDAO();
            weatherList = dao.selectWeather();

            return SUCCESS;
          }

        public List<Object> getWeatherList() {
            return weatherList;
        }

        public void setWeatherList(List<Object> weatherList) {
            this.weatherList = weatherList;
        }

    }

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

    以下のサンプルソースを作成
    weatherList.jsp
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Weather List</title>
    </head>
    <body>
    <table>
        <tr>
            <td>city</td>
            <td>temp_lo</td>
            <td>temp_hi</td>
            <td>prcp</td>
            <td>date</td>
        </tr>
        <s:iterator value="weatherList">
            <tr>
                <td><s:property value="city"/></td>
                <td align="center"><s:property value="temp_lo"/></td>
                <td align="center"><s:property value="temp_hi"/></td>
                <td align="center"><s:property value="prcp"/></td>
                <td><s:property value="date"/></td>
            </tr>
        </s:iterator>
    </table>
    </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.enable.DynamicMethodInvocation" value="false"/>
        <constant name="struts.devMode" value="true"/>
        <constant name="struts.allowlist.packageNames" value="test7.sample" />

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

            <action name="dbtest" class="test7.sample.action.WeatherListAction" method="execute">
                <result name="success">/weatherList.jsp</result>
            </action>

        </package>

        <!-- Add addition packages and configuration here. -->
    </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="test7" 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>test7</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>

    context.xmlファイル
    (プロジェクト名)\src\main\webapp\META-INFフォルダの下に作成
    以下のXMLファイルを作成。
    context.xmlファイル
    <?xml version="1.0" encoding="UTF-8"?>
    <Context reloadable="true">
      <Resource
        name="mydb"
        auth="Container"
        type="javax.sql.DataSource"
        driverClassName="org.postgresql.Driver"
        url="jdbc:postgresql://localhost:5432/mydb"
        username="testuser"
        password="userpass"
        validationQuery="select 1"/>
    </Context>

    4)htmlファイル
    (プロジェクト名)\src\main\webappフォルダをクリックし以下を実行
    新規アイコン→Web→HTMLファイル
    名前にindex.htmlを入力、完了をクリック。

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

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

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

    実行結果


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

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

参考1 コネクションプーリングの接続について

コネクションプーリングは、参考2のApache Commons DBCPのページを確認すると、デフォルトで初期接続数が0、最大接続数が8である。
接続数を確認するには、PostgreSQLをインストールした際一緒にインストールした「pg Admin 4」を使用する。
testuserの接続数が1あり、コネクションプーリングが行われていることが確認できる。

参考2 getter/setterについて

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

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

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

  4. 実行例

参考3

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