控制層是 Spring Boot 應用面向客戶端的接口層。它接收 HTTP 請求,調用對應的服務層方法,並返回相應的響應。
StudentController 負責處理 /api/v1/student 下的所有 HTTP 請求。
package com.example.demo.student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.time.Month;
import java.util.List;
@RestController
@RequestMapping(path = "api/v1/student")
public class StudentController {
    private final StudentService studentService ;
    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }
    @GetMapping
    public List<Student> getStudents() {
        return studentService.getStudents();
    }
    @PostMapping
    public void registerNewStudent (@RequestBody Student student) {
        studentService.addNewStudent(student);
    }
    @DeleteMapping(path = "{studentId}")
    public void deletStudent(@PathVariable("studentId") Long studentId) {
        studentService.deletStudent(studentId);
    }
    @PutMapping(path = {"{studentId}"})
    public void updateStudent(
            @PathVariable("studentId") Long studentId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String email ) {
        studentService.updateStudent(studentId, name, email);
    }
}
運行應用
完成後,應用將運行,並可以通過設置好的接口進行學生信息的增查改刪等操作。