LoginSignup
4

More than 5 years have passed since last update.

初めてのSTS(Helloworld)

Last updated at Posted at 2016-12-05

Helloworld

目的:ブラウザからアクセスしてHelloworldが表示される。


STS環境前提
Version: 3.8.2.RELEASE
Build Id: 201610040743
Platform: Eclipse Neon.1 (4.6.1)


以下、プロジェクト作成時に作成されるmainクラス。

HelloworldApplication.java
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloworldApplication {

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


新規クラスを作成し、以下のように変更する。

HelloworldApplication.java
package com.example;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @RequestMapping ("/hello")
    public String hoge() {
      System.out.println("HelloWorld!!");
        return "HelloWorld!!";
    }
}

STSにて以下を実行。
・プロジェクト右クリック-実行-Spring Boot アプリケーションを選択して実行する。
sts_hello1.png

コンソールにSpringのアスキーアートが表示される。
sts_hello2.png

ブラウザで[localhost:8080/hello]にアクセスする。
sts_hello3.png

@SpringBootApplication

このアノテーションを付けたパッケージ以下をコンポーネントスキャンの対象としてくれるため、アノテーションベースの開発が簡単に行える。

@SpringBootApplication@Configuration@EnableAutoConfiguration@ComponentScanを呼び出す。
@ComponentScan@Componentを全部使えるようにしてくれるので、@Componentを含む@Controllerが有効になる。

@RequestMapping

URLとメソッドのマッピングを行う。method属性によって同一URLのリクエストでもPOSTリクエスト時に処理するメソッドとGETリクエスト時に実行するメソッドといった細かなマッピングを行うことができる。

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