0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Tomcat・PostgreSQL連携

Last updated at Posted at 2022-05-03

お勉強用(備忘)

目的

・アプリサーバ(Tomcat)からデータソース経由でPostgreSQLに接続する。
・JSPにてデータソースを使ってPostgreSQLのテーブルデータを表示させる。

環境

VM:VirtualBox6.1
OS:Red Hat Enterprise Linux release 8.5 (Ootpa)
Java:openjdk version "17.0.3" 2022-04-19 LTS
Tomcat:apache-tomcat-9.0.62
PosgreSQL: PostgreSQL 13.6

前提条件

・接続先のデーベース(PostgreSQL)の準備ができていること。
 →PostgreSQL13.6 構築
・アプリサーバ(Tomcat)からデータベースに接続ができること

1.JAVAをインストール

[root@tomcat ]#
mkdir -pm 777 /tmp/Installer/java/
dnf install --downloadonly java-17-openjdk-devel --downloaddir=/tmp/Installer/java/

cd /tmp/Installer/java/;pwd
dnf localinstall ./*

>インストール済み:
>  java-17-openjdk-1:17.0.3.0.6-2.el8_5.x86_64                     java-17-openjdk-devel-1:17.0.3.0.6-2.el8_5.x86_64
>  java-17-openjdk-headless-1:17.0.3.0.6-2.el8_5.x86_64            ttmkfdir-3.0.9-54.el8.x86_64
>  xorg-x11-fonts-Type1-7.5-19.el8.noarch
>
>完了しました!

▽Javaの変更(ver8からver17に変更)

[root@tomcat ]#
alternatives --config java

>  選択       コマンド
>-----------------------------------------------
>*+ 1           java-1.8.0-openjdk.x86_64 (/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.302.b08-3.el8.x86_64/jre/bin/java)
>   2           java-17-openjdk.x86_64 (/usr/lib/jvm/java-17-openjdk-17.0.3.0.6-2.el8_5.x86_64/bin/java)
>
>Enter を押して現在の選択 [+] を保持するか、選択番号を入力します:2

[root@tomcat ]#
java -version
>openjdk version "17.0.3" 2022-04-19 LTS
>OpenJDK Runtime Environment 21.9 (build 17.0.3+6-LTS)
>OpenJDK 64-Bit Server VM 21.9 (build 17.0.3+6-LTS, mixed mode, sharing)

2.Tomcatインストール

▽ユーザ作成

[root@tomcat ]#
useradd -m tomcat

▽資材をダウンロード

[root@tomcat ]#
mkdir -pm 777 /tmp/Installer/tomcat
cd /tmp/Installer/tomcat/;pwd
wget https://dlcdn.apache.org/tomcat/tomcat-9/v9.0.62/bin/apache-tomcat-9.0.62.tar.gz

ll -h /tmp/Installer/tomcat/

▽解凍

[root@tomcat ]#
tar -xvf apache-tomcat-9.0.62.tar.gz -C /opt
chown -R tomcat: /opt/apache-tomcat-9.0.62

▽シンボリックリンク作成

ln -sv /opt/{apache-tomcat-9.0.62,tomcat}

▽変数定義

#変数定義
cat<<EOF>/etc/sysconfig/tomcat
JAVA_HOME="/usr/lib/jvm/jre"
CATALINA_HOME="/opt/tomcat"
CATALINA_BASE="/opt/tomcat"
CATALINA_OPTS="-server -Xmx128m -Xms128m -XX:MaxMetaspaceSize=128m"
EOF

#確認
cat /etc/sysconfig/tomcat

▽サービスファイル作成

cat<<EOF>/usr/lib/systemd/system/tomcat.service
[Unit]
Description=Apache Tomcat application server.
After=network.target
[Service]
Type=forking
User=tomcat
Group=tomcat
EnvironmentFile=/etc/sysconfig/tomcat
ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/opt/tomcat/bin/shutdown.sh
[Install]
WantedBy=multi-user.target
EOF

#確認
cat /usr/lib/systemd/system/tomcat.service

▽サービス起動

#サービス起動
systemctl daemon-reload
systemctl enable tomcat.service
systemctl start tomcat.service

systemctl status tomcat.service

>● tomcat.service - Apache Tomcat application server.
>   Loaded: loaded (/usr/lib/systemd/system/tomcat.service; enabled; vendor preset: disabled)
>   Active: active (running) since Mon 2022-05-02 23:18:34 JST; 11h ago
>  Process: 64206 ExecStop=/opt/tomcat/bin/shutdown.sh (code=exited, status=0/SUCCESS)
>  Process: 64231 ExecStart=/opt/tomcat/bin/startup.sh (code=exited, status=0/SUCCESS)
> Main PID: 64239 (java)
>    Tasks: 31 (limit: 10474)
>   Memory: 247.2M
>   CGroup: /system.slice/tomcat.service
>            64239 /usr/lib/jvm/jre/bin/java -Djava.util.logging.config.file=/opt/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava>

3.sample.warの配置

[root@tomcat ]#
cd /opt/tomcat/webapps;pwd

curl -O https://tomcat.apache.org/tomcat-9.0-doc/appdev/sample/sample.war
chown tomcat: /opt/tomcat/webapps/sample.war

ll -h /opt/tomcat/webapps
> drwxr-x---.  5 tomcat tomcat   86  5月  2 19:51 sample
> -rw-r--r--.  1 tomcat tomcat 4.5K  5月  2 19:51 sample.war

grep 'deploy' /opt/tomcat/logs/catalina.out
> 02-May-2022 19:51:51.759 情報 [Catalina-utility-1]org.apache.catalina.startup.HostConfig.deployWAR Web アプリケーションアーカイブ[/opt/apache-tomcat-9.0.62/webapps/sample.war] の配備は [217] ms で完了しました。

・sample画面確認
http://<IPアドレス>:8080/sample/
image.png

4.PostgreSQL用jdbcドライバーの配置

[root@tomcat ]#
#jdbcドライバーダウンロード
mkdir -m 777 /tmp/Installer/postgres
cd /tmp/Installer/postgres/;pwd
curl -O https://jdbc.postgresql.org/download/postgresql-42.3.4.jar

ll /tmp/Installer/postgres/
chown tomcat: /tmp/Installer/postgres/*

#libフォルダにjdbcドライバーを移動
mv /tmp/Installer/postgres/postgresql-42.3.4.jar /opt/tomcat/lib/
ll -h  /opt/tomcat/lib/ | grep postgresql
> -rw-r--r--. 1 tomcat tomcat 1016K  5月  2 22:03 postgresql-42.3.4.jar

5.データソース設定

・context.xml バックアップ

[root@tomcat ]#
cp -p /opt/tomcat/conf/context.xml{,_\`date +%Y%m%d\`}
ll -h /opt/tomcat/conf/context.xml*

・context.xml 編集

[root@tomcat ]#
cat /opt/tomcat/conf/context.xml
vi /opt/tomcat/conf/context.xml
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<Context>
    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- PostgreSQL -->
    <Resource name="jdbc/PostgreSQL"
      auth="Container"
      type="javax.sql.DataSource"
      factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
      initialSize="2" maxActive="4" minIdle="1" maxIdle="2"
      username="test_user01" password="password"
      driverClassName="org.postgresql.Driver" url="jdbc:postgresql://<DB・IPアドレス>:5432/testdb"
      validationQuery="SELECT 1" />
</Context>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

6.Tomcatサービス再起動

[root@tomcat]# 
systemctl restart tomcat.service
systemctl status tomcat.service

>● tomcat.service - Apache Tomcat application server.
>   Loaded: loaded (/usr/lib/systemd/system/tomcat.service; enabled; vendor preset: disabled)
>   Active: active (running) since Mon 2022-05-02 23:18:34 JST; 11h ago
>  Process: 64206 ExecStop=/opt/tomcat/bin/shutdown.sh (code=exited, status=0/SUCCESS)
>  Process: 64231 ExecStart=/opt/tomcat/bin/startup.sh (code=exited, status=0/SUCCESS)
> Main PID: 64239 (java)
>    Tasks: 31 (limit: 10474)
>   Memory: 247.2M
>   CGroup: /system.slice/tomcat.service
>            64239 /usr/lib/jvm/jre/bin/java -Djava.util.logging.config.file=/opt/tomcat/conf/logging.properties -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djdk.tls.ephemeralDHKeySize=2048 -Djava>

7.データソース接続確認

[root@tomcat]# 
lsof -Pi:5432
> COMMAND    PID   USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
> java    114747 tomcat   50u  IPv6 797431      0t0  TCP tomcat9:56292-> <DB・IPアドレス>:5432 (ESTABLISHED)
> java    114747 tomcat   52u  IPv6 797441      0t0  TCP tomcat9:56296-> <DB・IPアドレス>:5432 (ESTABLISHED)
> java    114747 tomcat   54u  IPv6 797443      0t0  TCP tomcat9:56300-> <DB・IPアドレス>:5432 (ESTABLISHED)
> java    114747 tomcat   56u  IPv6 797447      0t0  TCP tomcat9:56308-> <DB・IPアドレス>:5432 (ESTABLISHED)
> java    114747 tomcat   58u  IPv6 797445      0t0  TCP tomcat9:56304-> <DB・IPアドレス>:5432 (ESTABLISHED)
> java    114747 tomcat   60u  IPv6 797449      0t0  TCP tomcat9:56312-> <DB・IPアドレス>:5432 (ESTABLISHED)
> java    114747 tomcat   62u  IPv6 797451      0t0  TCP tomcat9:56316-> <DB・IPアドレス>:5432 (ESTABLISHED)

8.JSP作成

・テストJSP用フォルダ作成

[root@tomcat]# 
mkdir -m 750 /opt/tomcat/webapps/testjsp
chown tomcat: /opt/tomcat/webapps/testjsp
ll -h /opt/tomcat/webapps/

> drwxr-x---.  2 tomcat tomcat   44  5月  3 01:47 testjsp

・JSPファイル作成

[root@tomcat]# 
vi /opt/tomcat/webapps/testjsp/test.jsp
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<!DOCTYPE html>
<html>
    <head>
        <title>test.jsp</title>
    </head>
    <body>
     <p><font size="7" color="#00ff00">JSPテストページ</font></p>
    </body>
</html>

<%@page import="javax.sql.DataSource"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.*" %>
<%@page import="javax.naming.InitialContext"%>
<%@page contentType="text/html" pageEncoding="UTF-8" session="false" %>
<%
        //コネクションを取得するjndi
        String jndi = "java:comp/env/jdbc/PostgreSQL";
        InitialContext context = null;
        Connection connection = null;
        Statement stmt = null;

        //コネクション取得処理
        try {
                context = new InitialContext();
                DataSource ds = (DataSource) context.lookup(jndi);
                connection = ds.getConnection();
                String sql = "SELECT * FROM test_t1 order by dt limit 3000;";
                PreparedStatement pstmt = connection.prepareStatement(sql);
                ResultSet result = pstmt.executeQuery();
                while ( result.next() ) {
                    // 表示などの処理
                    int id = result.getInt("id");
                    String data =result.getString("data");
                    String dt =result.getString("dt");
                    out.println("<p>");
                    out.println("id:" + id + ",data:" + data + ",time:"+ dt );
                    out.println("</p>");
                 }
        }
        finally {
                if (context != null) {
                        try {
                                context.close();
                        }
                        catch (Exception e) {
                        }
                }
                if (connection != null) {
                        try {
                                connection.close();
                        }
                        catch (Exception e) {
                        }
                }
                }
        }
%>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#ファイルのオーナ変更
[root@tomcat]# 
chown tomcat: /opt/tomcat/webapps/testjsp/test.jsp
chmod 755 /opt/tomcat/webapps/testjsp/test.jsp
ll -h /opt/tomcat/webapps/testjsp/test.jsp

> -rwxr-xr-x. 1 tomcat tomcat 2.0K  5月  3 12:02 /opt/tomcat/webapps/testjsp/test.jsp

9.テストページにアクセス

http://<IPアドレス>:8080/testjsp/test.jsp
image.png

参考リンク

Java Tomcatなどのアプリケーションサーバ+DBコネクションプール設定例
【Javaサーブレット&jsp入門#3】Select文を実行してPostgreSQLからデータを取得して一覧表示する
インフラって難しそう…と避け続けためちゃよわプログラマが、克服のために頑張ってサーバを構築してみた。WebAPサーバ編

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?