
Get
query - param
1. @ requestParam map<> - map으로 받기
2. @ requestParam String name ~~ - 변수로 받기
3. UserRequest userRequest - 객체로 받기
객체로 받는 방법이 제일 많이 사용된다.
path - variable
/path-variable/{id}
@PathVariable(name = "id") String pathName)
{}안의 값이 받는 변수값이랑 다를땐 name지정을 해줘야 한다.
Post
requestParam으로 받을 수도 있긴하다.
get과 차이점은 쿼리가 바디로 숨겨져서 들어오는 것.
그러나 현재는 대부분 Json을 이용한다.
Json
1. @RequestBody , Map<String , Object>로 받기
2. @RequestBody RequestDto requestdto 로 받기
put도 requestBody로 받아야한다.
만약, 클래스에는 phoneNumber로 선언되어있는데 키값 phone_number로 들어온다면? , 스네이크케이스도 아니고 카멜케이스도 아닌경우라면(ex 대문자로만 이루어짐)?
1. 필드 선언 위에 JsonProperty("phone_number") 붙여 주면 phone_number로 들어와도 받을 수 있음
2. 클래스 단위로 룰을 적용시킬 수 있다. 일괄적으로 네이밍 룰 적용.
@JsonNamimg (value = PropertyNamingStrategy.SnakeCaseStrategy.class)
실제 post req 처리 과정
req -> ObjectMapper -> object -> method -> object -> object mappper -> json
response내려주는 방법
1. text
2. json
3. responseEntity
응답에 대해 customizing이 필요하면 ResponseEntity를 사용해라. (권장)
JsonInclude(JsonInclude.Include.NON_NULL) 하면 null값 제외하고 응답한다.
int는 기본값이 0이기 때문에 null리턴하고 싶으면 integer로 바껴야 함
restController 붙이면 responseBody붙이지 않아도 리턴하는 객체들에 대해 json만들어서 내려줄 수 있다.
page리턴하는 controller는 pageController만들어서 모으고 그게 아니면 restController에 모은다. (page리턴을 @respondeBody 필요없으니까)
Object Mapper
text JSON -> Object로 바꿔주고, Object를 JSON으로 바꿔준다.
1. object -> text
var user = new User( "steve" ,10);
var text = objectMapper.writeValueAsString(user); - user에 get메서드 있어야 함.
2. text -> object
var objectUser = objectMapper.readValue(text, User.class); - user에 기본 생성자 있어야 함.
objectMapper가 참조하는 클래스에는 get메서드를 사용하면 안됨. getter제외
objectMapper를 통해서 json노드에 접근하는 방법
maven repository 사이트에 접속하여 jackon core dependency를 설정파일에 추가한다.
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user); - user객체를 json string으로
JsonNode jsonNode = objectMapper.readTree(json);
String _name = jsonNode.get("name").asText(); - json내의 name필드값 반환
int _age = jsonNode.get("age").asInt(); - json내의 ageㄹ필드값 반환
JsonNode cars = jsonNode.get("cars"); - cars는 List<Car>, asList없음.
ArrayNode arrayNode = (ArrayNode)cars; - cars가 배열이니까 배열로 변환시킴
List<Car> _cars = objectMapper.convertValue(arrayNode, new TypeReference<List<Car>>(){}); - convertValue 는 object를 우리가 원하는 타입으로.
ObjectNode objectNode = (ObjectNode) jsonNode; - 값을 바꿀 수 있는 ObjectNode
objectNode.put("name","steve");
objectNode.put("age",20);
sout(objectNode.toPrettyString()); - json예쁘게 출력
'Spring' 카테고리의 다른 글
| [ Spring ] 트랜잭션 (0) | 2022.12.12 |
|---|---|
| [ Spring ] 의존성 주입 방법 (feat.lombok) (0) | 2022.11.23 |
| [ Spring ] Swagger이란 (0) | 2022.11.17 |
| [ Spring ] restTemplate (0) | 2022.11.11 |
| [spring] 어노테이션 (Annotaions) (0) | 2022.11.04 |