iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 12
0

上一章介紹了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依賴注入?


上一篇
Day 11 - Controller And RESTful (1)
下一篇
Day 13 - 什麼是IOC控制反轉? 什麼是DI依賴注入?
系列文
Spring Boot and React - 前後端 30 天分手日記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言