Spring MVC의 Controller로 사용되며, 클래스 선언을 단순화 시켜주는 어노테이션이다.
Spring에서 Controller 중 View로 응답하지 않는 Controller를 의미한다.
Method의 반환 결과를 JSON 형태로 반환한다.
@RestController
어노테이션이 적혀있는 Controller의 method는 HTTPResponse로 바로 응답 가능하다.
👉 즉 @ResponseBody
역할을 자동적으로 해주는 어노테이션이다.
@Controller
와 @RestController
의 차이점@Controller
- API와 view를 동시에 사용하는 경우에 사용하며, view
리턴이 주 목적이다.
- API 서비스로 대신 사용하는 경우에는 @ResponseBody
를 사용해 객체를 반환한다.
@RestController
- view가 필요없는 API만 지원하는 서비스에서 사용하며, data
리턴이 주 목적이다.
- @RequestMapping
메서드가 기본적으로 @ResponseBody
의 의미를 가정한다.
👉
@RestController
=@Controller
+@ResposeBody
POST
나 PUT
, PATCH
로 요청을 받을 때, Request로 넘어온 body 값들을 자바 타입으로 파싱해준다.POST
요청에 대해 request body에 있는 request message에서 값을 얻어와 매핑한다. 그 후 RequestData를 바로 Model이나 클래스로 매핑한다.@PostMapping("/api/posts")
public PostResponseDto createPost(@ReqeustBody PostRequestDto reeustDto) {
return postService.createPost(requestDto);
}
GET
/POST
/PUT
/PATCH
/DELETE
를 정의하기도 한다GET
이 적용된다.@RequestMapping("/")
public String index(Model model) {
model.addAttribute("list", bannerService.listAll());
return "index";
;}
{특정값}
을 변수로 받아올 수 있다.http://localhost:8080/api/posts/1
@GetMapping("/api/posts/{id}")
public PostResponceDto getPost(@PathVariable Long id) {
return postService.getPost(id);
}
?name=rara
와 같은 쿼리 파라미터를 파싱해 가져와 method의 파라미터에 사용한다.GET
요청에 따라 매칭되는 Requset 파라미터 값이 자동으로 들어간다.http://localhost:8080/home?user_id=rara.log
@PathVariable
과 유사하다.@GetMapping("/account")
public List<AccountInfo> getAccountByUserId (@RequestParam("user_id") Long userId) {
return accountService.getAccountByUserId(userId)
.stream().map(AccountDto -> AccountInfo.builder()
.ccountNumber(AccountDto.getAccountNumber())
.balance(AvvountDto.getBalance())
.build())
.collect(Collectors.toList());
}
@ReqeustPart("file") MultipartFile file
/courses
/courses/{id}
@RestController
public class CourseController {
@Autowired
private CourseRepository repository;
// http://localhost:8080/courses
@GetMapping("/course")
public List<Couse> getAllCourse() {
return repository.finAll();
}
// http://localhost:8080/courses/1
@GetMapping("/courses/{id}")
public Course getCourseDetails(@pathVariable long id) {
Optional<Course> course = repository.findById(id);
if(course.isEmpty()) {
throw new RuntimeException("Course not found with id" + id);
}
return course.get();
}
}
/course
@RestController
public class CourseController {
@Autowired
private CourseRepository repository;
// ...
@PostMapping("/courses")
public void createCourse(@RequestBody Course course) {
repository.save(course);
}
}
/courses/{id}
@RestController
public class CourseController {
@Autowired
private CourseRepository repository;
// ...
@PutMapping("/courses/{id}")
public void updateCourse(@PathVariable long id, @RequestBody Course course) {
repository.save(course);
}
}
/courses/{id}
@RestController
public class CourseController {
@Autowired
private CourseRepository repository;
// ...
@DelelteMapping("/courses/{id}")
public void deleteCourse(@PathVariable long id) {
repository.deleteById(id);
}
}