「Javaふりがなプログラミング」の感想・備忘録

スポンサーリンク

書籍「Javaふりがなプログラミング」のまとめ。

点数

60点

感想

初心者向けの内容だった。
ただし、エディタにInteliJ IDEAを使っている、フレームワークとしてSpring Bootを使っている、など初心者向けとは思えない内容も含まれていた。

IntelliJ IDEAでの入力補完

  • psvm⇒public static void main
  • sout⇒System.out.println();
  • command + N(Macの場合)⇒ゲッター/セッター、コンストラクタ、メソッドのオーバーライド、などを自動生成。
    ※Windowsの場合はAlt + Insert

Scannerクラス

ScannerクラスのnextLineメソッドで、入力データをStringで取得することができる。

import java.util.Scanner; 
〜省略〜
Scanner scanner = new Scanner(System.in);
String inputText = scanner.nextLine();

ScannerクラスのhasNextIntメソッドはint変換できる場合にtrueを返す、nextIntメソッドはintとして入力データを取得する。

if (!scanner.hasNextInt()) {
  System.out.println("整数を入力してください。\n");
} else {
  int num = scanner.nextInt();
}

配列の初期化

String[] strings = {"aaa", "bbb"};

拡張for文

配列、ArrayList、HashSetなどをループさせる。

for (String str: strings) {

コンストラクタにはvoidを付けない

public class Util {
  private String msg= "";
  public Util(String msg) {
    this.msg = msg;
  }
}

ArrayList

import java.util.ArrayList; 
〜省略〜
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("text1");
stringList.add("text2");
stringList.add("text3");
System.out.println("stringList.get(0)=" + stringList.get(0)); // text1
stringList.remove(0); // 削除するとインデックスが振りなおされる
System.out.println("stringList.get(0)=" + stringList.get(0)); // text2

// 拡張for文にArrayListを使う
for (String str : stringList) {
  System.out.println("拡張for文:" + str);
}

Spring Boot

Spring Bootの特徴

  • 複雑な設定が不要
  • アノテーションで機能を実装できる
  • Tomcarが内包されているため動作確認が容易

Spring Bootプロジェクトの作成

Spring Initializr(https://start.spring.io/)というWebアプリを利用する。

設定内容

  • Project:Maven Project
  • Language:Java
  • Spring Boot:初期選択のまま
  • Artifct:プロジェクト名やパッケージ名に使われる文字列
  • Dependencies:ThymeleafとSpring Webを追加

手順

  1. Generateボタンをクリックするとプロジェクトファイルがダウンロードされる。
  2. IntelliJ IDEAのワークスペースに、解凍したフォルダを移動。
  3. Import Projectでフォルダ内のpom.xmlを選択⇒Mavenによるライブラリダウンロードが行われる。

Spring Bootプロジェクトの中身

src/main/java/パッケージ名/XxxApplication.java

@SpringBootApplication
public class FuriganaJavaSpringBootApplication {
  public static void main(String[] args) {
   SpringApplication.run(FuriganaJavaSpringBootApplication.class, args);
  }
}

@SpringBootApplicationアノテーションをmainメソッドを持つクラスに付与することで、Spring Bootアプリとして実行できる状態になる。

Hello World!

  1. src/main/java/パッケージ名/にcontrollerパッケージを作成する。
  2. src/main/java/パッケージ名/controller/にHelloController.Javaを作成する。
package info.ageo_soft.FuriganaJavaSpringBoot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}
  • 先頭行のpackage文は、ファイル生成時にIntelliJ IDEAによって自動的に追加される。
  • クラスの@Controllerアノテーションとメソッドの@GetMapping(“/hello”)アノテーションにより、/helloへのリクエストでhelloメソッドが呼び出されるようになる。
  • @Controllerや@GetMappingを入力すると、IntelliJ IDEAによって自動的にimport文が追加される。
  • 呼び出されたメソッドでは、htmlファイルの名前をreturnする。
  1. src/main/resources/templates/にhello.htmlを作成する。
  1. src/main/java/パッケージ名/XxxApplication.javaのmainメソッドを実行する。

モデルを使ったフォーム処理の作成

  1. src/main/java/パッケージ名/にmodelパッケージを作成する。
  2. 以下のようなモデルクラスを作成する。
package info.ageo_soft.FuriganaJavaSpringBoot.model;

public class FDat {
    public int getNum1() {
        return num1;
    }
    public void setNum1(int num1) {
        this.num1 = num1;
    }
    public int getNum2() {
        return num2;
    }
    public void setNum2(int num2) {
        this.num2 = num2;
    }
    public String getOpe() {
        return ope;
    }
    public void setOpe(String ope) {
        this.ope = ope;
    }
    public double getAns() {
        return ans;
    }
    public void setAns(double ans) {
        this.ans = ans;
    }
    private int num1 = 0;
    private int num2 = 0;
    private String ope = "";
    private double ans = 0;
}
  1. Thymeleafを使ってhtmlを作成する。

Thymeleafを使うと、HTMLにモデルを埋め込むことができる。

<html xmlns:th="http://www.thymeleaf.org">
<!-- 省略 -->
<form th:action="@{/result}" th:object="${fdat}" method="post">
    <input type="number" th:field="*{num1}" />
    <select th:field="*{ope}">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="×">×</option>
        <option value="÷">÷</option>
    </select>
    <input type="number" th:field="*{num2}" />
 <input type="submit"value="計算"/>
</form>
<html xmlns:th="http://www.thymeleaf.org">
<!-- 省略 -->
<p th:text="'答えは、' +  ${fdat.getAns()}" />
  1. コントローラーに処理を定義する。
  • フォーム画面では、引数で受け取ったModelのaddAttributeメソッドにモデルを渡す。
  • 結果画面では、@ModelAttributeアノテーションを付けた引数でモデルを受け取る。
@GetMapping("/form")
public String form(Model model) {
    model.addAttribute("fdat", new FDat());
    return "form";
}
@PostMapping("/result")
public String result(@ModelAttribute FDat fdat, Model model){
    calculate(fdat);
    model.addAttribute("fdat", fdat);
    return "result";
}

コメント