
@RequestParam()@RestController
@RequestMapping("/request-data")
public class RequestDataController {
@GetMapping("/request-param")
public String requestParam (
//@RequestParam(name="name") String name,
@RequestParam("name") String name,
@RequestParam(name="age") int age
){
return "이름: " + name + "나이: " + age;
}
}
Result

@RequestParam(name="age" , required=false) int age
required=false = false
@RequestParam(name="age" , required=false) Integer age
@RequestParam() String name,
@PathVariable()@GetMapping("/path-variable/{var}")
public String pathVariable(
@PathVariable(name="var") String var
){
return "읽은 경로 변수 : " + var;`
}
@GetMapping("/path-variable/{var}/{str}")
public String pathVariable(
@PathVariable(name="var") String var,
@PathVariable("str") String str
){
return "읽은 경로 변수 : " + var + " , " + str;
}
1,2번 종합 결과

⚠️주의
@PathVariable(name="str", required=false) String str
구문에서 우리의 생각으로는 required=false가 붙어서 필수 조건은 아니다 생각하지만
@GetMapping("/path-variable/{var}/{str}")
패턴이 일치 하지 않기 위해 404 Error 발생
해결방법
@GetMapping({
"/path-variable/{var}/{str}",
"/patg-variable/{var}/",
"/patg-variable/{var}"
})
모든 경로의 경우의 수를 입력하여 패턴의 경우의수를 증가시켜 패턴일치를 유발시킨다.
⚠️ 주의
패턴에 따라 원치 않는 결과값을 출력
@GetMapping("/path-variable/other")
public String otherPathVariable(){
return "other 메서드 호출";
}
GET http://localhost:4000/request-data/path-variable/another/another
.../another/another PathVariable에서 어떤걸 호출 해야할지 모르기에 충돌이 발생
Error 500
@GetMapping("/path-variable/{var}/another")
public String anotherPathVariable1 (
@PathVariable("var") String var
) {
return "another1 메서드 호출";
}
@GetMapping("/path-variable/another{var}")
public String anotherPathVariable2 (
@PathVariable("var") String var
) {
return "another2 메서드 호출";
}

@RequestBody()@PostMapping("/request-body")
public String requestBody(
@RequestBody String requestBody
){
return "request body data: " + requestBody;
}

@PostMapping("/request-body")
public String requestBody(
// @RequestBody String requestBody
@RequestBody SampleDto requestBody
) {
return "Request Body data : " + requestBody.getName() + ", " + requestBody.getAge();
}
//1. 직접 생성
class SampleDto{
//필드
private String name;
private int age;
//생성자
public SampleDto(){};
public SampleDto(String name, int age){
this.name = name;
this.age = age;
}
//setter
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
//getter
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
}
//2. lombok으로 정리
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
class SampleDto {
private String name;
private int age;
}
