4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Thymeleaf @RestController, @Controllerの違い

Last updated at Posted at 2020-05-13

概要

Thymeleafを扱う初心者が @Controller と @RestController の挙動の違いを知りたかったので,調べました.

#環境

  • springboot
  • IntellJ CE
  • Lombok

###はじめに
sprintboot を起動し,次のURLにアクセスします.
http://localhost:8080/〇〇

@ Controller

以下のようなコードで
http://localhost:8080/list
にアクセスすると,
main/resources/templates/list_display.html
のhtmlが画面に表示されます.(”list_display”という文字列がそのまま表示されるわけではない)

@Controller
public class AppController {
    @GetMapping("list")
    public String from_list(){
        return "list_display";
    }
}

@ RestController

一方,以下のようなcontrollerのファイルを作成し, @RestControllerを用いて,
http://localhost:8080/person
にアクセスすると,

@RestController
public class SampleController {
    @GetMapping("person")
    public Person person() {
        return new Person(123, "hogehoge", 40);
    }
}

以下の文字列がそのまま返されます.
{"id":123,"name":"hogehoge","age":40}

(以下のようなPerson クラスを別に作成しておいてください)


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class Person {
    Integer id;
    String name;
    Integer age;
}

###まとめ

  • resource/ 内のhtmlファイルを画面に表示したいときは,@RestController
  • 単に文字列を出力させたいときは,@Controller

を使いましょう.

  • 簡単ですが,自分の備忘録のためにまとめました.
4
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?