금융에 대한 모든 것

@RestController

 @RestController 어노테이션은 스프링 4 이상의 버전부터 지원하는 어노테이션으로, 컨트롤러 클래스에 @RestController 붙이면 메서드에 @ResponseBody 어노테이션을 붙이지 않아도 문자열과 JSON 등을 전송할 있습니다. 뷰를 리턴하는 메서드들을 가지고 있는 @Controller와는 다르게 @RestController 문자열, 객체 등을 리턴하는 메서드들을 가지고 있습니다.

 

@RestController로 문자열 전송하기

예시

@RestController
@RequestMapping("/main/*")
public class RestController {
        
    @RequestMapping("/hello")
    public String hello() {
            return "hello";
    }
}

http://localhost:8080/main/hello 접속하면 "hello" 문자열이 전송된 것을 확인할  있습니다.

 

 

@RestController로 커맨드 객체 전송

 커맨드 객체를 전송하기 위해서는 JSON 형태로 전송해야 하기 때문에 JSON 관련 라이브러리를 사용합니다.

 

pom.xml

<!--JSON-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.4</version>
</dependency>

 pom.xml 파일에  코드를 붙여 넣기 합니다.

 

예시

@RestController
@RequestMapping("/main/*")
public class RestController {
        
    @RequestMapping("/hello")
    public UserVO hello() {
    
            UserVO userVO = new userVO();
        userVO.setUserId("yunyc");
        userVO.setUserPassword("1234");
        userVO.setEmail("yunyc1024@gmail.com");
        
            return userVO;
    }
}

커맨드 객체인 UserVO 객체를 생성하여  속성들의 값을 넣어준 다음 해당 객체를 반환합니다.

 

결과

{"id":"yunyc", "password":"1234", "email":"yunyc@gmail.com"}

http://localhost:8080/main/hello로 접속하면 위와 같이 JSON의 형태로 해당 URL로 전송됩니다. 

 

@RestController로 컬렉션 객체 전송

 컬렉션도 커맨드 객체와 마찬가지로 컬렉션 객체 속성 값을 세팅하고 리턴하면 JSON 형태로 전송됩니다.

 

예시

@RestController
@RequestMapping("/main/*")
public class RestController {
        
    @RequestMapping("/hello")
    public List<UserVO> hello() {
    
        List<UserVO> userList = userService.selectUserList();
            
        for (int i = 0; i < 2; i++) {
          UserVO userVO = new userVO();
          
          userVO.setUserId("yunyc");
          userVO.setUserPassword(i);
          userVO.setEmail("yunyc@gmail.com");
          
          userList.add(userVO);
        
        }
            return userList;
    }
}

 

결과

{"id":"yunyc", "password":"0", "email":"yunyc@gmail.com"}
{"id":"yunyc", "password":"1", "email":"yunyc@gmail.com"}
{"id":"yunyc", "password":"2", "email":"yunyc@gmail.com"}

 

@RestController로 map 전달

 전달 방법은 커맨드 객체를 전달하는 방법과 같습니다.

 

예시

@RestController
@RequestMapping("/main/*")
public class RestController {
        
    @RequestMapping("/hello")
    public HashMap<String, Object> hello() {
    
        HashMap<String, Object> hashMap = new HashMap<String, Object>();
    
        hashMap.put("id", "yunyc");
        hashMap.put("password", "1234");
        hashMap.put("email", "yunyc@gmail.com");
        
        return hashMap;
    }
}

 

결과

{"id":"yunyc", "password":"1234", "email":"yunyc@gmail.com"}
반응형