上一章介紹了RESTful與Controller, 忘記的朋友可以看這
Day 11 - Controller And RESTful (1)
接下來我們要新增其他Controller
CertificateController.java
@RestController
@RequestMapping("/api")
public class CertificateController {
@Autowired
private CertificateRepository certificateRepository;
@GetMapping("/certificates")
public Collection<Certificate> certificates(){
return certificateRepository.findAll();
}
}
CompanyController.java
@RestController
@RequestMapping("/api")
public class CompanyController {
@Autowired
private CompanyRepository companyRepository;
@GetMapping("/companies")
public Collection<Company> companies() {
return companyRepository.findAll();
}
@GetMapping("/company/{id}")
public ResponseEntity<?> getCompany(@PathVariable Long id) {
Optional<Company> company = companyRepository.findById(id);
return company.map(response -> ResponseEntity.ok().body(company))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
}
ExamController.java
@RestController
@RequestMapping("/api")
public class ExamController {
@Autowired
private ExamInfoRepository examInfoRepository;
@GetMapping("/exams")
public Collection<ExamInfo> exams() {
return examInfoRepository.findAll();
}
}
VendorController.java
@RestController
@RequestMapping("/api")
public class VendorController {
@Autowired
private VendorRepository vendorRepository;
@GetMapping("/vendors")
public Collection<Vendor> vendors() {
return vendorRepository.findAll();
}
@GetMapping("/vendor/{id}")
public ResponseEntity<?> getVendor(@PathVariable long id) {
Optional<Vendor> vendor = vendorRepository.findById(id);
return vendor.map(response -> ResponseEntity.ok().body(vendor))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
}
新增完可以從瀏覽器輸入localhost, 看看是不是都能順利拿到數據了
下一章 Day 13 - 什麼是IOC控制反轉? 什麼是DI依賴注入?