@RestController //해당 클래스는 REST API를 처리하는 Controller
@RequestMapping("/api") //RequestMapping URI를 지정해주는 Annotation
// => 전체 주소가 ~/api/~로 시작을 한다는 의미
public class ApiController {
@GetMapping("/hello") //http://localhost:8080/api/hello
public String hello(){
return "hello spring boot!";
}
//1. 일반 GET MAPPING~
@GetMapping("/hello") //http://localhost:8080/api/get/hello
public String hello(){
return "GET hello!";
}
@GetMapping(path="/hi") //http://localhost:8080/api/get/hi
public String hi(){
return "hi!";
}
@RequestMapping(path="/hi2",method = RequestMethod.GET) //http://localhost:8080/api/get/hi2
//=> hi()와 같은 동작
public String hi2(){
return "hi2!";
}
//2. PATH VARIABLE GET MAPPING~
@GetMapping("/path-variable/{id}") //http://localhost:8080/api/get/path-variable/iiiddd
public String pathVariable(@PathVariable String id) //겟매핑 주소의 {} 속 이름과 매개변수 이름이 같아야 함
{
System.out.println("PathVariable : "+id);
return id;
}
@GetMapping("/path-variable2/{id}") //http://localhost:8080/api/get/path-variable2/iiiddd2
public String pathVariable2(@PathVariable(name="id") String pathId,String id) //path 매개변수의 이름을 다르게 지정할 수 있다
{
System.out.println("PathVariable : "+pathId);
return pathId+id;
}
//3. REQUEST PARAM
@GetMapping(path="/query-param") // /query-param?address=부산&name=jj ..
public String queryParam(@RequestParam Map<String,String> queryParam){ // {address:부산,,,} 같은 키-값들로 이루어진 사전 꼴
StringBuilder sb=new StringBuilder();
queryParam.entrySet().forEach(entry->{ //entrySet -> map의 set을 반환, forEach로 모든 요소 돌고, entry로 각 요소를 지칭
System.out.println(entry.getKey());
System.out.println(entry.getValue());
System.out.println("\n");
sb.append(entry.getKey()+" = "+entry.getValue()+"\n");
});
return sb.toString();
} //파라미터를 주는대로 받아옴
@GetMapping(path="/query-param2")
public String queryParam2(@RequestParam String name, // 처리하고 싶은 파라미터만 받아옴, 그 이외의 것들은 400 오류
@RequestParam String email,
@RequestParam int age){
System.out.println(name);
System.out.println(email);
System.out.println(age);
return name+" "+email+" "+age;
}
// 받아올 매개변수가 무진장 많아서 여기에 매번 적어주기 무리일 때 => dto 패키지를 만들어 그 안에 매개변수를 속성으로 가지는 클래스를 생성
// 그 클래스를 파라미터로 받아서 처리, @RequestParam <<이거 안붙는거 주의!
@GetMapping(path="/query-param3")
public String queryParam3(UserRequest userRequest){ //여기서는 없는 파라미터를 주소로 요청해도 오류는 안나지만 누락처리 됨
System.out.println(userRequest.getName());
System.out.println(userRequest.getEmail());
System.out.println(userRequest.getAge());
System.out.println(userRequest); //이것과 밑에 반환 값은 같은 것임
return userRequest.toString();
}
'BackEnd > 패캠' 카테고리의 다른 글
AOP (0) | 2022.01.19 |
---|---|
Ioc, DI (0) | 2022.01.18 |
모범사례 - Object Mapper (0) | 2022.01.17 |
Response 내려주기 및 모범사례 (0) | 2022.01.16 |
POST/PUT/DELETE API (0) | 2022.01.15 |
Comment