ページの作成
親となるページを選択してください。
親ページに紐づくページを子ページといいます。
例: 親=スポーツ, 子1=サッカー, 子2=野球
子ページを親ページとして更に子ページを作成することも可能です。
例: 親=サッカー, 子=サッカーのルール
親ページはいつでも変更することが可能なのでとりあえず作ってみましょう!
| この記事の要点 |
|---|
|
@RestController の基本
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public UserDto get(@PathVariable Long id) {
return userService.findById(id);
// ← 自動で JSON 化されてレスポンスボディに書き出される
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public UserDto create(@RequestBody UserCreateRequest req) {
return userService.create(req);
}
@PutMapping("/{id}")
public UserDto update(@PathVariable Long id, @RequestBody UserUpdateRequest req) {
return userService.update(id, req);
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable Long id) {
userService.delete(id);
}
}
@RestController vs @Controller
| 項目 | @RestController | @Controller |
|---|---|---|
| 用途 | REST API | HTML View 返却 |
| 戻り値 | JSON / XML として直接出力 | View 名として解釈、テンプレート探す |
| @ResponseBody | クラス全体に暗黙適用 | 個別メソッドに付ける必要 |
| 典型例 | 外部 API / SPA バックエンド | サーバサイドレンダリング |
レスポンスの型
① POJO / DTO(標準)
@GetMapping("/{id}")
public UserDto get(@PathVariable Long id) {
return userService.findById(id);
}
// → {"id": 1, "name": "Alice", "email": "..."}
② List / Map
@GetMapping
public List<UserDto> list() {
return userService.findAll();
}
@GetMapping("/summary")
public Map<String, Object> summary() {
return Map.of(
"total", 100,
"active", 80
);
}
③ ResponseEntity(ステータス・ヘッダ制御)
@GetMapping("/{id}")
public ResponseEntity<UserDto> get(@PathVariable Long id) {
return userService.findByIdOptional(id)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<UserDto> create(@RequestBody UserCreateRequest req) {
UserDto created = userService.create(req);
URI location = URI.create("/api/users/" + created.getId());
return ResponseEntity.created(location).body(created);
}
④ ストリーミング
@GetMapping(value = "/export", produces = "text/csv")
public ResponseEntity<StreamingResponseBody> export() {
StreamingResponseBody body = out -> {
userService.streamAll().forEach(user -> {
try {
out.write((user.toCsvLine() + "\n").getBytes(StandardCharsets.UTF_8));
} catch (IOException e) { throw new RuntimeException(e); }
});
};
return ResponseEntity.ok()
.header("Content-Disposition", "attachment; filename=\"users.csv\"")
.body(body);
}
例外ハンドリング
@RestController
public class UserController {
@GetMapping("/{id}")
public UserDto get(@PathVariable Long id) {
return userService.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
}
@ExceptionHandler(UserNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ErrorResponse handleNotFound(UserNotFoundException ex) {
return new ErrorResponse("USER_NOT_FOUND", ex.getMessage());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> handleValidation(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage())
);
return errors;
}
}
// グローバルエラーハンドラ
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleAll(Exception ex) {
log.error("Unexpected", ex);
return new ErrorResponse("INTERNAL_ERROR", "システムエラー");
}
}
関連記事
ページの作成
親となるページを選択してください。
親ページに紐づくページを子ページといいます。
例: 親=スポーツ, 子1=サッカー, 子2=野球
子ページを親ページとして更に子ページを作成することも可能です。
例: 親=サッカー, 子=サッカーのルール
親ページはいつでも変更することが可能なのでとりあえず作ってみましょう!
子ページ
子ページはありません
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript で base URL を取得する方法|window.location.origin
- 4 YouTube Data API v3 エラー一覧|403・400・404 の原因と対処
- 5 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 6 3Dグラフィックスとは|モデリング/レンダリング/主要ソフトウェア (Blender / Maya)
- 7 Spring Frameworkのアノテーション一覧
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- 【django】ログイン 認証機能 2026-09-08 03:22:09
- MySQL ERROR 1063 Incorrect column specifier for column|原因と直し方 2026-09-08 03:11:09
- 【PHPエラー】Object of class stdClass could not be converted to string 2026-09-07 07:46:04
- Julia Genie ローカル開発サーバ起動完全ガイド 2026-09-07 07:46:04
- Wi-Fi とは|規格と世代(Wi-Fi 4〜7)・周波数帯・CSMA/CA・WPA3 NEW 2026-09-07 07:45:13
- set コマンドでシェルオプションと位置パラメータを操作 | bash 2026-09-07 07:45:13
- JPEG(.jpg/.jpeg)画像形式の完全ガイド — 仕様・マジックナンバー・他形式との比較・EXIF 2026-09-07 07:45:13
- UE5 Get Overlapping Actorsで特定クラスだけ処理|Class Filter・Cast To 2026-09-07 07:45:13
- Linuxで特定拡張子のファイルを再帰削除|find -deleteの安全手順 2026-09-07 07:45:13
- Django CBVでテンプレートに値を渡す|get_context_data・extra_context 2026-09-07 07:45:13
- Linuxで複数ファイルの文字列を一括置換|find・sed・xargsの安全手順 2026-09-07 07:45:13
- Laravelルートグループ|prefix・middleware・nameで一括管理 2026-09-07 07:45:13
- Linux whichコマンドの使い方|絶対パス取得とtype・command -vの違い 2026-09-07 07:45:13
- Linux catコマンドの使い方|行番号表示・複数ファイル連結 2026-09-07 07:45:13
- unable to execute 'gcc': No such file or directory 2026-09-07 07:45:13
コメントを削除してもよろしいでしょうか?