스프링

[Spring] Controller의 파라미터를 받는 여러 가지 방법 (Parameter Mapping 방법)

여니여니_ 2021. 12. 1. 00:06

@PathVariable

중괄호를 활용하여 변수처럼 적고 http://localhost:8080/v1/product/10 과 같이 호출 가능하다. 

1
2
3
4
5
6
7
8
9
10
@RestController
    @RequestMapping(path = "/v1")
    public class TestController {
 
        // 상품 조회
        @GetMapping(path = "/product/{productId}")
        public Product selectProduct(@PathVariable(name = "productId") Integer productId) {
 
            return productService.getProductBy(productId);
        }
 
cs

 

@RequestParam

http://localhost:8080/v1/product?category=fruit 과 같이 호출 가능하다. 

required 디폴트 값은 true인데 category와 같이 선언한 파라미터가 없을 경우 오류를 발생한다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
 @RestController
    @RequestMapping(path = "/v1")
    public class TestController {
 
        // 카테고리로 상품 조회
        @GetMapping(path = "/product")
        public Response<List<String>> getProducts(@RequestParam(name = "category",required = falseString category) {
 
            return productService.getProductByCategory(category);
        }
 
cs

 

@RequestBody

JSON, XML 형식으로 전송된 데이터를 받을 때 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 var data= {
        id: 1,
        name"apple",
        description: "sweet, delicious apple",
        price: 1000
        
    };
 
    $.ajax({
        url: "/RequestBody",
        type: "POST",
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: "application/json; UTF-8;"
    });
 
cs
1
2
3
4
5
6
7
@PostMapping("/RequestBody")
    @ResponseBody
    public Product RequestBody(
            @RequestBody Product product
    ) {
        return product;
    }
 
cs

 

'스프링' 카테고리의 다른 글

[Spring] Entity, DTO, VO 비교하기  (0) 2021.12.01
[Spring] directory 구성 (계층형/도메인형)  (0) 2021.12.01
토비의 스프링 4장 예외  (0) 2021.11.22