새소식

[5분 내로] 강의실/📋 Spring Annotation이란?

[Spring] 스프링 @RestController란? 그리고 사용방법

  • -
728x90

안녕하세요. 팀드모네입니다.

오늘은 스프링어노테이션 중 @RestController라는 것에 대해서 알아보겠습니다.

 

1. @RestController란?

- 스프링프레임워크 4.x 버전 이상부터 사용가능한 어노테이션으로 @Controller에 @ResponseBody가 결합된 어노테이션입니다. 컨트롤러 클래스에 @

RestController를 붙이면, 컨트롤러 클래스 하위 메서드에 @ResponseBody 어노테이션을 붙이지 않아도 문자열과 JSON 등을 전송할 수 있습니다.

 

2. @Controller와 @RestController 차이점

*@Restcontroller는 

Spring MVC Controller에 @ResponseBody가 추가된 것입니다. 따라서 @Controller와 달리 @RestController는 컨트롤러 클래스의 각 메서드마다 @ResponseBody를 추가할 필요가 없어졌습니다.

 

3. @RestController를 사용하여 문자열을 전송하는 방법

1
2
3
4
5
6
7
8
9
@RestController
@RequestMapping("/hello/*")
public class RestController {
    
    @RequestMapping("/test")
    public String test() {
        return "test";
    }
}
cs

 

4. @RestController를 사용하여 map을 전송하는 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
@RequestMapping("/hello/*")
public class RestController {
    
    @RequestMapping("/test")
    public HashMap<StringObject> test() {
    
        HashMap<StringObject> hashMap = new HashMap<StringObject>();
    
        hashMap.put("name""john");
        hashMap.put("age""32");
        hashMap.put("gender""man");
        
        return hashMap;
    }
}
cs

 

추가로 궁금한 점이 있다면 댓글에 남겨주세요.

 

다음 포스팅은 스프링프레임워크 어노테이션인 @RequestMapping에 대해서 알아보겠습니다.

다음 포스팅으로 이동 >> 

https://doctorson0309.tistory.com/406

 


reference : https://spring.io

reference : https://webcoding.tistory.com/entry/Spring-REST-API-사용하기

광고 링크 : 플랫폼공작소플랫폼공작소TV쇼핑몰


 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.