2020년 5월 12일 화요일

[Spring] Using @RestController

@RestController

 The @RestController Annotation is an annotation that supports spring 4-point versions, and only @RestController is attached to the controller class to send strings, JSON, and so on without having to attach @ResponseBody Annotation to the method. Unlike @Controller, which has methods to return views, @RestController has methods to return strings, objects, etc.

Transferring strings to @RestController

example
@RestController
@RequestMapping("/main/*")
public class RestController {
 
    @RequestMapping("/hello")
    public String hello() {
     return "hello";
    }
}
If you connect to http://localhost:8080/main/hello, you can see that the string "hello" was sent.

Send command objects to @RestController

 Use JSON-related libraries because sending command objects requires transmission in the form of JSON.

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

example
@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;
    }
}
Paste the above code into the pom.xml file.

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


Send collection objects to @RestController

 As with the command object, the collection is sent in the form of JSON when the value of the collection object property is set and returned.

example
@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;
    }
}

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

Pass map to @RestController

 The delivery method is the same as the delivery of a command object.

example
@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;
    }
}

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

댓글 없음:

댓글 쓰기