LoginSignup
4
8

More than 3 years have passed since last update.

Webシステム構築(超基礎)②:APサーバ構築と基本動作

Last updated at Posted at 2019-12-25

目的

Webシステム構築を目的として、超基礎的なAPサーバの構築と動作を確認する。
(APサーバとしてはTomcatを利用する。)

環境条件

  • APサーバ
    • EC2:t2.micro
    • OS:Red Hat Enterprise Linux 8 (HVM), SSD Volume Type
    • Disk:汎用SSD(GP2) 10GB
    • Tomcat:Apache Tomcat 9
    • Java:JDK 1.8

セキュリティグループの設定等はいい感じに。

構築手順

ec2-userでログイン

rootユーザにスイッチ
$ sudo su - 

openjdkパッケージの存在確認
# yum info java-*-openjdk

openjdkパッケージのインストール
# yum install -y java-1.8.0-openjdk
Complete!の出力を確認する。

javaのインストール確認
# java -version
openjdk version "1.8.0_232"
OpenJDK Runtime Environment (build 1.8.0_232-b09)
OpenJDK 64-Bit Server VM (build 25.232-b09, mixed mode)

専用ユーザ(tomcat)の作成
# useradd -s /sbin/nologin tomcat

Tomcatのバイナリファイルのダウンロード
# curl -O http://ftp.riken.jp/net/apache/tomcat/tomcat-9/v9.0.30/bin/apache-tomcat-9.0.30.tar.gz

Tomcatのバイナリファイルをインストールディレクトリに移動
# mv apache-tomcat-9.0.30.tar.gz /opt/

Tomcatのバイナリファイルを解凍
# cd /opt
# tar zxvf apache-tomcat-9.0.30.tar.gz

Tomcatのファイル群の所有者変更
# chown -R tomcat:tomcat apache-tomcat-9.0.30

Tomcatのサービス登録のための登録ファイル作成
# vi /etc/systemd/system/tomcat.service

========================================
[Unit]
Description=Apache Tomcat 9
After=network.target

[Service]
User=tomcat
Group=tomcat
Type=oneshot
PIDFile=/opt/apache-tomcat-9.0.30/tomcat.pid
RemainAfterExit=yes

ExecStart=/opt/apache-tomcat-9.0.30/bin/startup.sh
ExecStop=/opt/apache-tomcat-9.0.30/bin/shutdown.sh
ExecReStart=/opt/apache-tomcat-9.0.30/bin/shutdown.sh;/opt/apache-tomcat-9.0.30/bin/startup.sh

[Install]
WantedBy=multi-user.target
========================================

作成したファイルの権限変更
# chmod 755 /etc/systemd/system/tomcat.service

Tomcatのサービス登録
# systemctl enable tomcat

Tomcatサービスの停止を確認
# service tomcat status
   Active: inactive (dead)の出力を確認する。

Tomcatサービスを起動する
# service tomcat start
Redirecting to /bin/systemctl start tomcat.service

再度Tomcatサービスのステータスを確認する
# service tomcat status
   Active: active (exited)の出力を確認する。 

ブラウザからWebサーバの「パブリックDNS:8080」に接続し、
Apache Tomcat/9.0.30のWelcome Pageが表示されることを確認する。

APサーバの基本動作

JSPとJavaプログラムを利用した簡単なWebアプリケーションを構築し、APサーバ上で動作させる。
Web画面上で二つの数字を入力すると、その足し算の結果を処理して返すという単純なアプリケーションである。

test.jsp
<!DOCTYPE html>
<html>
    <head>
        <title>requestForm</title>
    </head>
    <body>
        <p>値を入力してください</p>

        <%-- GETメソッドでテキストを送信 --%>
        <form action="./TestServlet">
            <p>
                数字を入力してください。
            </p>
            <p>
                <input type="text" name="text1"> + <input type="text" name="text2"> =
            </p>
            <input type="submit" value="確定">
        </form>
    </body>
</html>
TestServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * コンストラクタ.
     */
    public TestServlet() {
        super();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String inputText1 = ""; // テキスト1格納用変数
        String inputText2 = ""; // テキスト2格納用変数
        int num1 = 0; // テキスト1の数値化用変数
        int num2 = 0; // テキスト2の数値化用変数

        inputText1 = request.getParameter("text1");
        inputText2 = request.getParameter("text2");

        num1 = Integer.parseInt(inputText1);
        num2 = Integer.parseInt(inputText2);

        int res = num1 + num2;

        // 画面に出力する内容の設定
        // 出力する内容がHTMLであることを設定
        response.setContentType("text/html");
        // 出力する画面の文字コードをUTF-8に設定
        response.setCharacterEncoding("UTF-8");

        // 画面に出力するためのWriterクラスインスタンスを取得
        PrintWriter pw = response.getWriter();

        // HTMLを出力
        pw.println("<html>");
        pw.println("<head>");
        pw.println("<title>計算結果</title>");
        pw.println("</head>");
        pw.println("<body>");
        pw.println("<h1>計算結果</h1>");
        pw.println("<p>" + inputText1 + " + " + inputText2 + " = " + res + "</p>");
        pw.println("</body>");
        pw.println("</html>"); 
    }
}

TestServlet.javaについては、ライブラリ含めてJarファイルとして準備する。(TestServlet.jar)

アプリケーションを動作させるための環境準備

必要なディレクトリの作成
# cd /opt/apache-tomcat-9.0.30/webapps
# mkdir -p test/WEB-INF/lib

web.xmlファイルの作成
# vi test/WEB-INF/web.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.
-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  version="3.1">

    <servlet>
        <servlet-name>TestServlet</servlet-name>
            <servlet-class>TestServlet.TestServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>TestServlet</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>

</web-app>
========================================

アプリケーションのデプロイ

以下、ディレクトリ構成に合うようにTestServlet.jarとtest.jspを配置する。

/opt/apache-tomcat-9.0.30/webapps/test

test/
├── test.jsp
└── WEB-INF
    ├── lib
    │   └── TestServlet.jar
    └── web.xml

動作確認

Tomcatサービスを再起動する
# service tomcat restart
Redirecting to /bin/systemctl start tomcat.service

ブラウザからWebサーバの「パブリックDNS:8080/test/test.jsp」に接続し、
作成したWebページの表示及び、処理の動作が正しく行われることを確認する。

次回は、
Webシステム構築(超基礎)③:DBサーバ構築と基本動作
です。

4
8
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
4
8