Quellcode durchsuchen

Transform Student Contoller to REST Contoller

Eldar Mukhtarov vor 10 Monaten
Ursprung
Commit
46f8a72302

+ 34 - 9
project/backend_springboot/src/main/java/pl/dmcs/eldarmuk/backend_springboot/controller/StudentController.java

@@ -1,17 +1,42 @@
 package pl.dmcs.eldarmuk.backend_springboot.controller;
 
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.*;
+
 import pl.dmcs.eldarmuk.backend_springboot.model.Student;
+import pl.dmcs.eldarmuk.backend_springboot.repository.StudentRepository;
+
+import java.util.List;
 
-@Controller
+@RestController
+@CrossOrigin(origins = "http://localhost:4200")
+@RequestMapping("/students")
 public class StudentController {
+    private StudentRepository studentRepository;
+
+    @Autowired
+    public StudentController(StudentRepository studentRepository) {
+        this.studentRepository = studentRepository;
+    }
+
+    @GetMapping
+    public List<Student> findAllStudents() {
+        return studentRepository.findAll();
+    }
 
-    @GetMapping("/student")
-    public String getStudent(Model model) {
-        Student student = new Student(1L, "John", "Doe", "john.doe@example.com");
-        model.addAttribute("student", student);
-        return "student";
+    @DeleteMapping("/{id}")
+    public ResponseEntity<?> deleteStudent(@PathVariable("id") long id) {
+        try {
+            Student student = studentRepository.findById(id);
+            if (student == null) {
+                return ResponseEntity.notFound().build();
+            }
+            studentRepository.deleteById(id);
+            return ResponseEntity.ok(student);
+        } catch (Exception e) {
+            return ResponseEntity.status(500).body("Error deleting student: " + e.getMessage());
+        }
     }
 }

+ 1 - 0
project/backend_springboot/src/main/java/pl/dmcs/eldarmuk/backend_springboot/repository/StudentRepository.java

@@ -7,4 +7,5 @@ import org.springframework.data.jpa.repository.JpaRepository;
 @Repository
 public interface StudentRepository extends JpaRepository<Student, Long> {
     Student findById(long id);
+    // Student findByAccountUsername(String username);
 }

+ 1 - 1
project/backend_springboot/src/main/resources/application.properties

@@ -1,4 +1,4 @@
-#spring.application.name=backend_springboot
+spring.application.name=backend_springboot
 spring.mvc.view.prefix=/WEB-INF/views/
 spring.mvc.view.suffix=.jsp