LoginSignup
0
0

@Controllerと@RestControllerの違い

Last updated at Posted at 2023-09-07

序文

編集履歴 無し
備忘録兼JavaDocを参考文献として提示しているものがなかったため文章を作成。 間違い・補足可能な情報があり次第追記する。

結論

@RestController@Controllerの拡張版。
@ResponceBody@Controllerと合併している。

補足

昔は@RestControllerは存在せず、
@ResponceBody@Controllerを両方付与する必要があった模様。

HTMLを返す際には@Controllerをまだ用いれるが、
統一して@RestControllerを使用して問題なさそう。

テスト:JSON形式を返す想定(@Controller

SampleAPI.java
@Controller
public class SampleAPI{

  @GetMapping("/")
	public Text main() {
		return new Text("Hello");
	}

}
record Text(String message){};

スクリーンショット 2023-09-07 23.50.04.png

error.log
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path []: would dispatch back to the current handler URL [/] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause

jakarta.servlet.ServletException: Circular view path []: would dispatch back to the current handler URL [/] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

テスト:JSON形式を返す想定(@RestController

SampleAPI.java
@RestController
public class SampleAPI{

  @GetMapping("/")
	public Text main() {
		return new Text("Hello");
	}

}
record Text(String message){};

スクリーンショット 2023-09-07 23.49.27.png

RestControllerのみJSON形式のデータを返すことができていることが確認できた。
@Controllerの方はビューリゾルバを提供しろとエラーを吐いていることも確認できた。

参考サイト

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