Skip to content

Commit

Permalink
Controller 2
Browse files Browse the repository at this point in the history
  • Loading branch information
thethirdlane committed Jul 20, 2022
1 parent 9b95558 commit ba61d87
Showing 1 changed file with 41 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
package ttl.larku.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import ttl.larku.domain.Student;
import ttl.larku.service.StudentService;

import java.net.URI;
import java.util.List;

/**
Expand All @@ -28,9 +33,12 @@ public class StudentController {
// }

@GetMapping("/{id}")
public Student getStudent(@PathVariable("id") int id) {
public ResponseEntity<?> getStudent(@PathVariable("id") int id) {
Student s = studentService.getStudent(id);
return s;
if(s == null) {
return ResponseEntity.status(404).body("No student with id: " + id);
}
return ResponseEntity.ok(s);
}

@GetMapping
Expand All @@ -40,9 +48,38 @@ public List<Student> getAllStudents() {
}

@PostMapping
public Student insertStudent(@RequestBody Student student) {
public ResponseEntity<?> insertStudent(@RequestBody Student student) {
Student newStudent = studentService.createStudent(student);

return newStudent;
URI newResource = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(newStudent.getId())
.toUri();

//return ResponseEntity.created(newResource).body(newStudent);
return ResponseEntity.created(newResource).build();
}

@DeleteMapping("/{id}")
public ResponseEntity<?> deleteStudent(@PathVariable("id") int id) {
boolean b = studentService.deleteStudent(id);
if(!b) {
return ResponseEntity.status(404).body("No student with id: " + id);
}
else {
return ResponseEntity.noContent().build();
}
}

@PutMapping
public ResponseEntity<?> updateStudent(@RequestBody Student student) {
boolean b = studentService.updateStudent(student);
if(!b) {
return ResponseEntity.status(404).body("No student with id: " + student.getId());
}
else {
return ResponseEntity.noContent().build();
}
}
}

0 comments on commit ba61d87

Please sign in to comment.