Spring

Request 파라미터 실습

코린이엄현종 2024. 3. 20. 16:03
package com.eom.controllerexercise.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {

    @RequestMapping(value = "/post")
    public String getPost(@RequestParam(name = "category") String category,
                          @RequestParam(name = "id") Integer id) {
        return "You requested " + category + " - " + id + "post";
    }
}

 

http://localhost:8080/post?category=it&id=10 검색을 하면

 

category = it  String category 에 저장

id = 10             Integer id 에 저장

 

return "You requested " + category (it) + " - " + id (10) + "post";

 

 

 

id는 필수적이지만 category는 선택적

package com.eom.controllerexercise.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {

    @RequestMapping(value = "/post")
    public String getPost(@RequestParam(required = false) String category,
                          @RequestParam Integer id) {
        return "You requested " + category + " - " + id + "post";
    }
}

 

http://localhost:8080/post?id=10 을 검색 (category 생략)

 

오류 페이지는 나오지 않고 category 값은 null 값

 

package com.eom.controllerexercise.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RequestParamController {

    @RequestMapping(value = "/post")
    public String getPost(@RequestParam(required = false, defaultValue = "it") String category,
                          @RequestParam Integer id) {
        return "You requested " + category + " - " + id + "post";
    }
}

 

defaultValue = "it"

category에 it가 저장

 

 

http://localhost:8080/post?id=10&category=spring 

 

데이터가 들어오지 않으면 defaultValue = it 값을 사용하지만 실제 전송 하는 RequestParam이 있으면 전송 되는 값을 사용한다.

 

 

 

@PathVariable

 

PathParam을 사용하기 위해서는 Path에 {} 형태가 되어 있으면 이 부분에 PathParam이 전달 된다는 것

@RequestMapping(value = "/user/{type}/id/{id}")
public String getUser(@PathVariable(name = "type") String type,
                      @PathVariable(name = "id") Integer id) {
    return "You requested " + type + " - " + id + "user";
}

 

http://localhost:8080/user/admin/id/10

admin 이 {type} 에 들어가는 값

10 은 {id} 에 들어가는 값

 

return "You requested " + type (admin) + " - " + id (10) + "user";