Skip to content

05 - Controller แรก

บทนี้จะสร้าง endpoint แรกของระบบ เพื่อให้เห็นว่า Spring Boot รับ request และตอบ response ได้อย่างไร

หลังจบบทนี้ เราจะมี:

GET /hello
GET /health

Controller คือ class ที่อยู่หน้าสุดของ backend สำหรับรับ HTTP request จาก client ใน Spring Boot เราใช้ @RestController เพื่อบอกว่า class นี้เป็น REST controller

สร้างไฟล์:

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;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello Spring Boot";
}
}

บน Windows:

Terminal window
.\gradlew.bat bootRun

จากนั้นเปิด browser หรือ Postman:

GET http://localhost:8080/hello

ควรได้:

Hello Spring Boot

@RestController บอก Spring ว่า class นี้รับ HTTP request และค่าที่ return จาก method จะเป็น response body

@GetMapping("/hello") บอกว่า method นี้รับ HTTP GET ที่ path /hello

method hello() return String ดังนั้น response ที่ client เห็นคือ text ธรรมดา

เพิ่ม 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 “ปัญหาที่พบบ่อย”

ตรวจว่า path ถูกต้องหรือไม่ เช่น /hello ไม่ใช่ /Hello

ตรวจว่า HelloController อยู่ใต้ package หลัก เช่น:

com.example.backendapi.controller

ถ้า controller อยู่นอก package หลัก Spring อาจ scan ไม่เจอ

กลับไปดู log ใน terminal ก่อนเสมอ เพราะ Spring Boot มักบอกสาเหตุชัดเจน เช่น port ชน หรือ bean error

บทนี้ถือว่าสำเร็จเมื่อ:

  • GET /hello ตอบ Hello Spring Boot
  • GET /health ตอบ OK
  • ทดสอบผ่าน browser หรือ Postman

แบบฝึกหัดท้ายบท

Section titled “แบบฝึกหัดท้ายบท”

เพิ่ม endpoint:

GET /version

ให้ตอบกลับ:

Backend API v1