오답노트
[Spring Boot] GET 본문
Controller 생성
@RestController
@RequestMapping("/api/get")
public class GetApiController {}
RestController와 RequestMapping Annotation을 사용하여 컨트롤러 클래스를 생성한다.
GetMapping 과 RequestMapping
GetMapping
path 를 지정하여 해당 주소를 GET방식으로 요청할 때 실행할 API를 구현 할 수 있다.
@GetMapping(path="/hello")
public String getHello(){
return "get Hello";
}
RequestMapping
GetMapping 보다는 전통적인 방식으로 path와 method를 지정하여 API를 구현 할 수 있다.
@RequestMapping(path = "/hi",method = RequestMethod.GET)
public String hi(){
return "get hi";
}
PathVariable
주소에 있는 변수를 추출할 수 있다. 주소를 정의하는 Annotation에서 {}를 통해 가져올 주소 위치와 변수명을 선택할 수 있다.
또한 매개변수로 받을 때 어떤 변수에 PathVariable를 받을지도 명시적으로 표현할 수 있다.
// ../api/get/path-variable/{name}
@GetMapping("/path-variable/{name}")
public String pathVariable(String name){
System.out.println(name);
return name;
}
// ../api/get/path-variable/{name}
@GetMapping("/path-variable/{name}")
public String pathVariable(@PathVariable(name = "name") String pathName, String name){
System.out.println(pathName);
return pathName;
}
QueryParam
Map과 같은 Collection이나 매개변수 또는 클래스를 통해서 주소내의 쿼리문의 인자들을 추출할 수 있다.
Collection
// ../api/get/query-param?user=steve&email=steve@gmail.com&age=30
@GetMapping(path = "query-param")
public String queryParam(@RequestParam Map<String, String> queryParam){
StringBuilder sb = new StringBuilder();
queryParam.entrySet().forEach(e-> {
System.out.println(e.getKey());
System.out.println(e.getValue());
System.out.println();
sb.append(e.getKey() + " = " + e.getValue() + "\n");
});
return sb.toString();
}
Parameter
@GetMapping("query-param02")
public String queryParam02(
@RequestParam String name,
@RequestParam String email,
@RequestParam int age
){
System.out.println(name);
System.out.println(email);
System.out.println(age);
return name +" "+ email + " "+ age;
}
Class
@GetMapping("query-param03")
public String queryParam03(UserRequest userRequest){
System.out.println(userRequest.getName());
System.out.println(userRequest.getEmail());
System.out.println(userRequest.getAge());
return userRequest.toString();
}
public class UserRequest {
private String Name;
private String email;
private int age;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "UserRequest{" +
"Name='" + Name + '\'' +
", email='" + email + '\'' +
", age=" + age +
'}';
}
}
'Java > Spring' 카테고리의 다른 글
[Spring Boot] PUT (0) | 2023.07.12 |
---|---|
[Spring Boot] POST (0) | 2023.07.12 |
[Spring Boot] 스프링 부트란 (0) | 2023.07.12 |
[Web] HTTP Protocal (0) | 2023.07.12 |
[Web] URI 설계 패턴 (0) | 2023.07.12 |