0
0

More than 3 years have passed since last update.

Tomcatを使ってSquareに顧客登録する方法

Last updated at Posted at 2020-04-26

目次

  • EclipseでMavenプロジェクト作成
  • MavenプロジェクトにTomcat(Java Servlet API)とSquareを登録
  • 登録ページ作成(JSP作成)
  • 内部処理を作成-1-(JSPとの通信)
  • 内部処理を作成-2-(Squareとの通信)

EclipseでMavenプロジェクト作成

参考サイト[Eclipse/Tomcat] MavenのwebappプロジェクトでServlet+JSP

1. Eclipseのパッケージエクスプローラー内で右クリック

スクリーンショット 2020-04-26 4.39.07.png

2. 新規からMaven プロジェクトをクリック

スクリーンショット 2020-04-26 4.42.01.png

3.次へをクリック

  • (未選択)シンプルなプロジェクトの作成(アーキタイプ選択のスキップ)
  • (選択)デフォルト・ワークスペース・ロケーションの使用
  • (未選択)ワーキング・スペースへプロジェクトを追加
  • (未設定)拡張

スクリーンショット 2020-04-26 4.44.11.png

4.maven-archetype-webappを選択して次へ

※フィルターにコピペするなら→「org.apache.maven.archetypes」
スクリーンショット 2020-04-26 4.55.45.png

5.グループidアーティファクトidを入力して完了をクリック

簡単に説明すると

  • グループid自分の所属するグループ
  • アーティファクトidプロジェクト名

と考えれば良い。グループidを何にすればいいかわからないなら「com.〇〇」←○はTwitterの@を飛ばしたIDを入れればいい
詳しく知りたい方へ↓
Guide to naming conventions on groupId, artifactId, and version
EclipseでMavenプロジェクトを新規作成する(Java)

スクリーンショット 2020-04-26 4.59.35.png

6.自分が作成したMavenプロジェクトがあれば成功!

スクリーンショット 2020-04-26 5.09.05.png

7.JRE(Java Runtime Environment)のバージョンを1.7から11に変更(8でも可)

1.自分が作ったMavenプロジェクト内のJRE システム・ライブラリー[JavaSE-1.7]を右クリック
2.プロパティをクリック
スクリーンショット 2020-04-26 5.13.35.png

3.実行環境のJavaSE-1.7(java7)をクリック
スクリーンショット 2020-04-26 5.16.41.png

4.JavaSE-11(java11)をクリック
スクリーンショット 2020-04-26 5.18.32.png

5.JavaSE-11になってれば成功!
スクリーンショット 2020-04-26 5.21.15.png

8.欠けているフォルダーを復活!

1.自分が作ったMavenプロジェクト内のJRE システム・ライブラリー[JavaSE-11]を右クリック
2.ビルド・パスからビルド・パスの構成をクリック
スクリーンショット 2020-04-26 5.23.04.png

3.ソースを選択(一番上の「ソース」「プロジェクト」「ライブラリー」「順序およびエクスポート」「モジュール依存関係」)
4.適応して閉じるを選択
スクリーンショット 2020-04-26 5.25.16.png

4.欠けていたフォルダーが作成されれば成功!
スクリーンショット 2020-04-26 5.28.13.png

MavenプロジェクトにTomcat(Java Servlet API)を登録

参考サイト[Eclipse/Tomcat] MavenのwebappプロジェクトでServlet+JSP

1.作成したMavenプロジェクト内のpom.xmlをダブルクリック

スクリーンショット 2020-04-26 5.36.50.png

2.最新のJava Servlet APIのxmlコードをコピー

https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
↓記事作成時点(2020年04月26日)のxmlコード Ver:4.0.1

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>

3.挿入.....。

※記事作成時点では28行目()と29行目()の間に挿入
↓31行目から36行目に挿入されている
スクリーンショット 2020-04-26 5.44.47.png

4.最新のSquare SDKのxmlコードをコピー

https://search.maven.org/search?q=g:com.squareup%20AND%20a:square
↓記事作成時点(2020年04月26日)のxmlコード Ver:5.2.2.20200422

<dependency>
  <groupId>com.squareup</groupId>
  <artifactId>square</artifactId>
  <version>5.2.2.20200422</version>
</dependency>

5.挿入.....。

記事作成時点では36行目()と37行目()の間に挿入
↓37行目から41行目に挿入されている
スクリーンショット 2020-04-26 7.16.33.png

4.Maven依存関係に追加されていたら成功!

スクリーンショット 2020-04-26 7.19.58.png

登録ページ作成(JSP作成)

おまたせしました!準備は終わりましたのでこれからプログラミングをします!

1.作成したMavenプロジェクトの「src」→「main」→「webapp」→「WEB-INF」を右クリックして「新規」→「その他」をクリック

スクリーンショット 2020-04-26 7.23.59.png

2.「Web」の「JSPファイル」を選択して次へ

スクリーンショット 2020-04-26 7.29.08.png

3.ファイル名を入力して完了

私はMainServletにしました。
スクリーンショット 2020-04-26 7.31.45.png

4.名前(名字と名前)と送信ボタンを表示させます

MainServlet.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- ↓サイト名 -->
<title>square顧客登録ページ</title>
</head>
<body>
<!-- ↓送信先Java -->
<form action="./Main">
<p>名前</p>
<a>性</a>
<!-- ↓名字を入れるボックス -->
<input type="text" name="name1">
<a>名</a>
<!-- ↓名前を入れるボックス -->
<input type="text" name="name2">
<br>
<!-- ↓Jspに送信ボタン -->
<input type="submit" value="送信">
</form>
</body>
</html>

内部処理を作成-1-(JSPとの通信)

1.作成したMavenプロジェクトの「src/main/java」を右クリックして「新規」→「その他」をクリック

※src/main/javaがない場合→
スクリーンショット 2020-04-26 7.40.25.png

2.「Web」の「サーブレット」を選択して次へ

スクリーンショット 2020-04-26 7.42.36.png

3.クラス名を入力して完了

実際の業務でこれやると怒られるんだけどね...。
スクリーンショット 2020-04-26 7.44.33.png

4.作成されればこうなります↓

阿波根に殺されないように注意しましょう。ヘッドショット注意
スクリーンショット 2020-04-26 7.46.23.png

5.まずはjavaからjspに転送されるプログラムを書きます

変更(追加)した場所↓

Main.java
// JSPにforward(ファイルの場所指定)
String view = "/WEB-INF/MainServlet.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.forward(request, response);

全部↓

Main.java

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Main
 */
public class Main extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Main() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
//      response.getWriter().append("Served at: ").append(request.getContextPath());

        // JSPにforward(ファイルの場所指定)
        String view = "/WEB-INF/MainServlet.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

6.実行してみてJspに記載した内容が表示されればOK!

↓成功!
スクリーンショット 2020-04-26 7.59.08.png

↓文字化けした場合
スクリーンショット 2020-04-26 8.01.12.png

Main.java
response.getWriter().append("Served at: ").append(request.getContextPath());

↑これをコメントアウトしよう!

7.Jspで入力した文字をJavaで受け取ろう

説明:Jspの「id=name1」のテキストボックスの文字を「String name1」に入れる

Main.java
//jspから受け取り
String name1 = request.getParameter("name1");//名前(性)
String name2 = request.getParameter("name2");//名前(名)

7.nullだと実行しない用にする

説明:name1とname2がnullじゃなかったら実行

Main.java
if (name1 != null || name2 != null) {
}

8.空白だとエラーを出す

説明:name1とname2が空白じゃなかったら実行。空白だったらエラーを出す

Main.java
if (!name1.equals("") && !name2.equals("")) {
}else{
System.out.println("性・名を入力してください");
}

9.Square.javaに送るよ

説明:Square.javaに性と名を送る

Main.java
//squareに送信
Square square = new Square();
square.main(name1, name2);

10.ここまで記載した全部↓

Main.java
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import square.SquareMain;

/**
 * Servlet implementation class Main
 */
public class Main extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Main() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        //      response.getWriter().append("Served at: ").append(request.getContextPath());
        //jspから受け取り
        String name1 = request.getParameter("name1");//名前(性)
        String name2 = request.getParameter("name2");//名前(名)
        if (name1 != null || name2 != null) {
            if (!name1.equals("") && !name2.equals("")) {
                //squareに送信
                Square square = new Square();
                square.main(name1, name2);
                System.out.println("完了:");
            } else {
                System.out.println("性・名を入力してください");
            }
        }
        // JSPにforward(ファイルの場所指定)
        String view = "/WEB-INF/MainServlet.jsp";
        RequestDispatcher dispatcher = request.getRequestDispatcher(view);
        dispatcher.forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

内部処理を作成-2-(Squareとの通信)

参考にしたサイト「Java client library for the Square API

1.作成したMavenプロジェクトの「src/main/java」→「デフォルト・パッケージ」を右クリックして「新規」→「クラス」をクリック

スクリーンショット 2020-04-26 8.15.47.png

2.名前を入れて完了クリック

Eclipseにも注意受けます..。
スクリーンショット 2020-04-26 8.19.03.png

3.まずはアクセストークンを入力しましょう

↓テスト用

Square.java
SquareClient client = new SquareClient.Builder()
            .environment(Environment.SANDBOX)
            .accessToken("YOUR_SANDBOX_ACCESS_TOKEN")
            .build();

↓本番用

Square.java
SquareClient client = new SquareClient.Builder()
    .environment(Environment.PRODUCTION)
    .accessToken("ACCESS TOKEN HERE")
    .build();

4.CustomersAPI

詳細:「Customers

Square.java
CustomersApi api = client.getCustomersApi();

5.送信する形を作る

詳細:「Create Customer

Square.java
CreateCustomerRequest createCustomerRequest = new CreateCustomerRequest.Builder()
                .idempotencyKey("unique_idempotency_key")
                .givenName(name1)//性
                .familyName(name2)//名
                .address(null)//今回は使用しない
                .build();

6.送信するぞ!

Square.java
try {
            CreateCustomerResponse response = api.createCustomer(createCustomerRequest);
        } catch (ApiException e) {
            List<Error> errors = e.getErrors();
            int statusCode = e.getResponseCode();
            HttpContext httpContext = e.getHttpContext();

            // Your error handling code
            System.err.println("APIを呼び出すときのApiExceptionエラー");
            e.printStackTrace();
        } catch (IOException e) {
            // Your error handling code
            System.err.println("API呼び出し時のIOExceptionエラー");
            e.printStackTrace();
        }

7.Square.javaの全部

Square.java
import java.io.IOException;
import java.util.List;

import com.squareup.square.Environment;
import com.squareup.square.SquareClient;
import com.squareup.square.api.CustomersApi;
import com.squareup.square.exceptions.ApiException;
import com.squareup.square.http.client.HttpContext;
import com.squareup.square.models.CreateCustomerRequest;
import com.squareup.square.models.CreateCustomerResponse;
import com.squareup.square.models.Error;

public class Square {
    public void main(String name1, String name2) {
        SquareClient client = new SquareClient.Builder()
                .environment(Environment.PRODUCTION)
                .accessToken("ACCESS TOKEN HERE")
                .build();

        CustomersApi api = client.getCustomersApi();
        CreateCustomerRequest createCustomerRequest = new CreateCustomerRequest.Builder()
                .idempotencyKey("unique_idempotency_key")
                .givenName(name1)//性
                .familyName(name2)//名
                .address(null)//今回は使用しない
                .build();

        try {
            CreateCustomerResponse response = api.createCustomer(createCustomerRequest);
        } catch (ApiException e) {
            List<Error> errors = e.getErrors();
            int statusCode = e.getResponseCode();
            HttpContext httpContext = e.getHttpContext();

            // Your error handling code
            System.err.println("APIを呼び出すときのApiExceptionエラー");
            e.printStackTrace();
        } catch (IOException e) {
            // Your error handling code
            System.err.println("API呼び出し時のIOExceptionエラー");
            e.printStackTrace();
        }

    }
}

完成!

スクリーンショット 2020-04-26 4.23.37.png
スクリーンショット 2020-04-26 4.23.29.png

動画ので教える感覚で記事書くと見にくくなることがわかった。

次回から気をつけます

PS 挿入ってエロいよね

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