zkvn99

[Spring] 데이터 전달 본문

Language/Java

[Spring] 데이터 전달

zkvn1103 2023. 9. 16. 17:41

Spring Framework에서 데이터를 컨트롤러로 값을 전달하는 방법

 

  • @RequestParam: HTTP 요청 파라미터를 받을 때 사용됩니다. 일반적으로 URL의 쿼리 문자열로 전달되는 데이터를 처리합니다.
    @GetMapping("/example")
    public String example(@RequestParam String parameterName) {
        String message = "example";
        return message;
    }

    
    @ResponseBody
    @PostMapping("/login/mailAuthentication")
    public ResponseEntity<String> mailConfirm(@RequestParam("email") String email) throws Exception {
        if(!memberService.findByMemberEmail(email)){
            String code = registerMailService.sendSimpleMessage(email);
            return ResponseEntity.ok(code); // 200 OK with the code
        } else {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("중복된 이메일입니다."); // 409 Conflict
        }
    }

 

  • @PathVariable: URL 경로의 일부를 변수로 받을 때 사용됩니다. 주로 RESTful API에서 사용됩니다.
@GetMapping("/example/{id}")
public String example(@PathVariable Long id) {
    // ...
}

 

  • @RequestHeader: HTTP 요청 헤더 값을 받을 때 사용됩니다.
@GetMapping("/example")
public String example(@RequestHeader("User-Agent") String userAgent) {
    // ...
}

 

  • @RequestAttribute: HTTP 요청 속성(attribute) 값을 받을 때 사용됩니다. 주로 인터셉터나 필터에서 설정한 속성을 컨트롤러로 전달할 때 사용됩니다.
@GetMapping("/example")
public String example(@RequestAttribute("attributeName") String attributeValue) {
    // ...
}

 

  • @PathVariable, @RequestParam, @RequestHeader 조합: 다양한 데이터를 조합하여 받을 수도 있습니다.
@GetMapping("/example/{id}")
public String example(@PathVariable Long id, @RequestParam String queryParam, @RequestHeader("User-Agent") String userAgent) {
    // ...
}

 

 

  • @MatrixVariable: 행렬 변수를 받을 때 사용됩니다. RESTful API에서 행렬 변수를 사용하는 경우에 유용합니다.
@GetMapping("/example")
public String example(@MatrixVariable String variableName) {
    // ...
}

 

  • 커스텀 어노테이션  ArgumentResolver: 필요에 따라 커스텀 어노테이션을 만들고 ArgumentResolver 구현하여 데이터를 컨트롤러로 전달할  있습니다.  방법은 고급 사용자 정의 기능을 구현할  사용됩니다.
@GetMapping("/example")
public String example(@CustomAnnotation String customValue) {
    // ...
}

 

이번에 Restful API를 만들면서 JSON 형태를 많이 다루게 되어서 정리해보았다.

'Language > Java' 카테고리의 다른 글

[Java] Exception Handling  (1) 2023.08.01
[Java] Basic Syntax  (0) 2023.07.30
[Java] 코딩테스트 자주 쓰는 메서드  (0) 2023.06.27
[Java] Array & Collection  (0) 2023.05.27
[Java] int 배열 vs Integer 배열  (0) 2023.05.26