Kita buat folder baru dengan nama "controller" kemudian buat class baru dengan nama ProductController.java
package ryunze.apidasar.controller;
public class ProductController {
// ...
}
Buat anotasi @RestController
Ini menunjukan jika class tsb. sebagai Rest Controller sebuah endpoint.
package ryunze.apidasar.controller;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
// ...
}
Untuk class ini, kita akan handle semua request ke endpoint /api/products
Tambahkan anotasi @RequestMapping
package ryunze.apidasar.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
@RequestMapping("/api/products")
public class ProductController {
// ...
}
Handle Request
Import package untuk anotasi handle method GET:
import org.springframework.web.bind.annotation.GetMapping;
Import juga package java Map dan HashMap karena di Springboot otomatis menampilkan JSON berdasarkan Object dari Java.
import java.util.Map;
import java.util.HashMap;
Kita akan coba handle request dengan method GET ke endpoint /api/products
Buat method baru dengan nama showAll() dengan tipe data Map<String, Object> dan tambah anotasi @GetMapping
package ryunze.apidasar.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Map;
import java.util.HashMap;
@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping
public Map<String, Object> showAll() {
Map<String, Object> data = new HashMap<>();
data.put("status", "success");
data.put("code", 200);
return data;
}
}
Simpan dan run. Cek url localhost:8080/api/products
Jika muncul response yang sesuai berarti berhasil ya 👋 Di postingan berikut kita tampilkan menggunakan Service yang datanya diambil dari Model biar lebih rapi.

Top comments (0)