Skip to content

Instantly share code, notes, and snippets.

@evrentan
Created June 13, 2021 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evrentan/01bc8d6e98ebdcaf94145324339676ea to your computer and use it in GitHub Desktop.
Save evrentan/01bc8d6e98ebdcaf94145324339676ea to your computer and use it in GitHub Desktop.
StudentController
package com.tan.myhateoasexample.controller;
import com.tan.myhateoasexample.dto.Student;
import com.tan.myhateoasexample.dto.StudentRef;
import com.tan.myhateoasexample.service.IStudentService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping(value = "/student", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public class StudentController {
private final IStudentService studentService;
public StudentController(IStudentService studentService) {
this.studentService = studentService;
}
@GetMapping(produces = {"application/hal+json"})
ResponseEntity<CollectionModel<StudentRef>> getAllStudentRefList() {
List<StudentRef> studentRefList = this.studentService.getAllStudentRefList();
CollectionModel<StudentRef> studentRefCollectionModel = null;
if (CollectionUtils.isNotEmpty(studentRefList)) {
final Link link = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(StudentController.class).getAllStudentRefList()).withSelfRel();
studentRefCollectionModel = CollectionModel.of(studentRefList, link);
}
return Optional.ofNullable(studentRefCollectionModel)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@GetMapping(value = "/{studentId}", produces = {"application/hal+json"})
ResponseEntity<Student> getStudentById(@PathVariable final String studentId) {
final Student student = this.studentService.getStudentById(studentId);
return Optional.ofNullable(student)
.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping
ResponseEntity<Student> createStudent(@RequestBody Student student) {
return ResponseEntity.ok(this.studentService.createStudent(student));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment