05 - Controller แรก
เป้าหมายของบท
Section titled “เป้าหมายของบท”บทนี้จะสร้าง endpoint แรกของระบบ เพื่อให้เห็นว่า Spring Boot รับ request และตอบ response ได้อย่างไร
หลังจบบทนี้ เราจะมี:
GET /helloGET /healthController คืออะไร
Section titled “Controller คืออะไร”Controller คือ class ที่อยู่หน้าสุดของ backend สำหรับรับ HTTP request จาก client ใน Spring Boot เราใช้ @RestController เพื่อบอกว่า class นี้เป็น REST controller
สร้าง HelloController
Section titled “สร้าง HelloController”สร้างไฟล์:
src/main/java/com/example/backendapi/controller/HelloController.javaใส่โค้ด:
package com.example.backendapi.controller;
import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;
@RestControllerpublic class HelloController {
@GetMapping("/hello") public String hello() { return "Hello Spring Boot"; }}รัน application
Section titled “รัน application”บน Windows:
.\gradlew.bat bootRunจากนั้นเปิด browser หรือ Postman:
GET http://localhost:8080/helloควรได้:
Hello Spring Bootอธิบายโค้ด
Section titled “อธิบายโค้ด”@RestController บอก Spring ว่า class นี้รับ HTTP request และค่าที่ return จาก method จะเป็น response body
@GetMapping("/hello") บอกว่า method นี้รับ HTTP GET ที่ path /hello
method hello() return String ดังนั้น response ที่ client เห็นคือ text ธรรมดา
เพิ่ม health endpoint
Section titled “เพิ่ม health endpoint”เพิ่ม method ใน class เดิม:
@GetMapping("/health")public String health() { return "OK";}ทดสอบ:
GET http://localhost:8080/healthควรได้:
OKทำไม health endpoint มีประโยชน์
Section titled “ทำไม health endpoint มีประโยชน์”ในระบบจริง health endpoint ใช้ตรวจว่า application ยังตอบ request ได้หรือไม่ ต่อไปเราสามารถต่อยอดเป็น Spring Boot Actuator ได้
ปัญหาที่พบบ่อย
Section titled “ปัญหาที่พบบ่อย”404 Not Found
Section titled “404 Not Found”ตรวจว่า path ถูกต้องหรือไม่ เช่น /hello ไม่ใช่ /Hello
Controller ไม่ถูก scan
Section titled “Controller ไม่ถูก scan”ตรวจว่า HelloController อยู่ใต้ package หลัก เช่น:
com.example.backendapi.controllerถ้า controller อยู่นอก package หลัก Spring อาจ scan ไม่เจอ
Application ไม่ start
Section titled “Application ไม่ start”กลับไปดู log ใน terminal ก่อนเสมอ เพราะ Spring Boot มักบอกสาเหตุชัดเจน เช่น port ชน หรือ bean error
Checkpoint
Section titled “Checkpoint”บทนี้ถือว่าสำเร็จเมื่อ:
GET /helloตอบHello Spring BootGET /healthตอบOK- ทดสอบผ่าน browser หรือ Postman
แบบฝึกหัดท้ายบท
Section titled “แบบฝึกหัดท้ายบท”เพิ่ม endpoint:
GET /versionให้ตอบกลับ:
Backend API v1