war {
enabled = true
archiveName='demo.war' // <-ここはプロジェクトに合わせて書き換えてください
}
package jp.kobespiral.hello;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloController {
private ArrayList<String> list = new ArrayList<>();
@GetMapping("{name}/hello")
public String SayHelloRequestParam(@PathVariable String name, Model model) {
model.addAttribute("greeting", createGreetingMessage());
model.addAttribute("name", name);
return "hello";
}
@PostMapping("{name}/hello/add")
public String addHello(@PathVariable String name, @RequestParam("text") String text, Model model) {
list.add(text);
model.addAttribute("greeting", text);
model.addAttribute("name", name);
return "post_hello";
}
private String createGreetingMessage() {
if (this.list.size() == 0) {
return "挨拶がまだ登録されていません";
}
String greeting = "";
for (String s : this.list) {
greeting = greeting + s + "、";
}
return greeting;
}
}<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
</head>
<body>
<h1>ここはhello.htmlです</h1>
<div>[あいさつ文]</div>
<p th:text="${greeting}"></p>
<div>[本文]</div>
<p>[[${name}]]さん、Spring Bootへようこそ!</p>
<div>FORM</div>
<form action="./add" method="post">
<div>
<label for="text">挨拶を入力</label>
<input name="text" id="text" />
</div>
<div>
<button>POST</button>
</div>
</form>
</body>
</html>package jp.kobespiral.hello;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
@RestController
@RequestMapping("/api")
public class HelloRestController {
@GetMapping("/hello")
public String SayHelloRestRequestParam() {
return "Hello APIをGETで呼び出しました!";
}
@PostMapping("/hello")
public String SayHelloPostMethod(@RequestParam("name") String name) {
return name + "さん、こんにちは! hello APIをPOSTで呼び出しました!";
}
}./gradlew.bat war
2020-06-03 中村
これまではWebサービスやWebアプリの作成を想定して, warファイルを作るプロジェクトを学んできた.
この時,
$ ./gradlew.bat war
作成されるwarは,Tomcatサーバのwebappsフォルダに デプロイし運用するものである.
その一方で,Webサーバにデプロイせずにローカルの マシンで実行可能なwar(実行可能WAR)も作ることができる.
gradle でターゲットbuildを指定する.
$ ./gradlew.bat build
プロジェクトのbuild/libsに,
hogehoge-SNAPSHOT0.0.1.war
ができるので,それをターミナルからJavaで実行する
$ java -jar hogehoge-SNAPSHOT0.0.1.war
warの中にWebサーバが入っていて,
http://localhost:ポート番号/
でブラウザでアクセスできる.