Talend API Tester - Free Edition
Visually interact with REST, SOAP and HTTP APIs.
chrome.google.com
server.port = 9090
package com.example.hello.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // 해당 class : restApi 처리하는 controller로 등록됨
@RequestMapping("/api") // URI을 지정해주는 annotation
public class ApiController {
@GetMapping("/hello") // http://localhost:8080/api/hello 로 매핑
public String hello(){
return "hello spring boot";
}
}
@RestController
@RequestMapping("/api/get")
public class GetApiController {
//@RequestMapping("/hi") // get, post, put, delete 다 동작해버림
@RequestMapping(path= "/hi", method= RequestMethod.GET) // get만 동작함 http://localhost:8080/api/get/hi
public String hi(){
return "hi";
}
//RequestMapping + RequestMethod.GET == GetMapping <<< <<< <<<
@GetMapping(path = "/hello") // http://localhost:8080/api/get/hello
public String hello(){
return "get Hello";
}
// http://localhost://8080/api/get/path-variable/{name}
@GetMapping("/path-variable/{name}")
//public String pathVariable(@PathVariable String name){ // {}안의 이름과 같아야 함. 이름다르게 되야할경우?
public String pathVariable(@PathVariable(name = "name") String pathName, String name){ // pathName에 name값이 들어가게 됨
System.out.println("PathVariable : " + pathName);
return pathName;
}
>>> http://localhost:8080/api/get/path-variable/java >>> java return함
//http://localhost:8080/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( 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();
}
// 명확하게 사용할 queryParam key가 정해져있는 경우엔?
@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 ;
}
// queryParam 받기 3번째 : dto만들기 (제일 많이씀)
// 알수없는 값(dto에 없는)이 들어올경우는 >> 그값은 매칭안됨
@GetMapping("query-param03") // @RequestParam 붙이지 않음
public String queryParam03(UserRequest userRequest){
System.out.println(userRequest.getName());
System.out.println(userRequest.getEmail());
System.out.println(userRequest.getAge());
return userRequest.toString() ;
}
package com.example.hello.dto;
public class UserRequest {
private String name;
private String email;
private int age;
public String getName() {
return name;
}
~~~~
1. post
package com.example.hello.dto;
public class PostRequestDto {
private String account;
private String email;
private String address;
private String password;
public String getAccount() {
return account;
}
@RestController
@RequestMapping("/api")
public class PostApiController {
@PostMapping("/post")
//public void post(@RequestBody Map<String, Object> requestData){
// requestData.forEach((key, value) -> {
// System.out.println("key : " + key);
// System.out.println("value : " + value);
// });
//} >> 이렇게하면 뭐가들어오는지 모름 dto로 하기 >>
@PostMapping("/post")
public void post(@RequestBody PostRequestDto requestData){
System.out.println(requestData);
}
}
>> 요즘 application/json default : utf-8 (예전엔 json:charset-utf-8 << 지정해야했음)
@JsonProperty("phone_number")
private String phoneNumber;
@JsonProperty("OTP")
private String OTP;
public class PutRequestDto {
private String name;
private int age;
private List<CarDto> carList;
public String getName() {
return name;
}
======================
public class CarDto {
private String name;
@JsonProperty("car_number")
private String carNumber;
public String getName() {
return name;
}
@JsonNaming(value = PropertyNamingStrategies.SnakeCaseStrategy.class)
public class PutRequestDto {
@RestController
@RequestMapping("/api")
public class PutApiController {
@PutMapping("/put/{userId}")
public PutRequestDto put(@RequestBody PutRequestDto requestDto, @PathVariable(name="userId") Long id){
System.out.println(id);
return requestDto;
}
}
>> 굳이 문자열로 바꾸고 지랄발광안해도 됨
@RestController
@RequestMapping("/api")
public class DeleteApiController {
@DeleteMapping("/delete/{userId}")
public void Delete(@PathVariable String userId, @RequestParam String account){
System.out.println("userId"+userId);
System.out.println("account" + account);
}
@RequestParam vs @PathVariable
@PathVariable은 어떤 요청이든 간에 딱 하나만 쓸 수 있습니다.
4. 정리/요약
1) @RequestParam 과 @PathVariable은 둘 다 데이터를 받아오는 데에 사용한다!
2) @PathVariable은 값을 하나만 받아올 수 있으므로, 쿼리스트링 등을 이용한
여러 개 데이터를 받아올 때는 @RequestParam을 쓴다!
3) @RequestParam은 uri를 통해 전달된 값이 아니더라도, ajax 요청을 통해 body에 담아온 데이터를
여러 타입으로 받을 수 있다.
ch5. loc, DI, AOP (0) | 2022.08.01 |
---|---|
ch4.7 & 4.8 reponse, object Mapper 모범사례 (0) | 2022.08.01 |
ch3. 웹개발 개론 (0) | 2022.07.28 |
ch2.6 옵저버, 2.7 파사드, 2.8 전략 패턴 (0) | 2022.07.28 |
Tip. loading time알아내기 (0) | 2022.07.27 |
댓글 영역