๐ ์์ฒญ(Request) ๋ฐ์ดํฐ ๋ฐ์์ค๊ธฐ
โซ๏ธ AddPostReqDto.java
@Data
public class AddPostReqDto {
private String title;
private String writer;
private String content;
private MultipartFile file;
private List<MultipartFile> files;
}
Request DTO ... @Getter
Ajax๋ฅผ ํตํด JSON ํํ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ค๋ฉด, ์คํ๋ง์ด DTO ๊ฐ์ฒด๋ก ๋ณํํ์ฌ ๊ฐ์ ธ์ค๋๋ก ํ๋ค.
์ด ๋ ์คํ๋ง์์ Json์ DTO ๊ฐ์ฒด๋ก ๋ง๋ค์ด์ฃผ๊ธฐ ์ํด ์ฌ์ฉํ๋ Jackson ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ Getter๋ก Json Key ๊ฐ์ ์์ฑํ๊ธฐ ๋๋ฌธ์ DTO ํด๋์ค์๋ @Getter ๊ฐ ๊ผญ ํ์ํ๋ค.
โซ๏ธ RequestTestController.java
@Slf4j
@RestController
public class RequestTestController {
@PostMapping("/api/v1/rp/post") // โญ ๊ฐ์ฒด๋ก ๋ฐ๊ธฐ
public ResponseEntity<?> addPost(@RequestParam String title,
@RequestParam String writer,
@RequestParam String content) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", title);
map.put("writer", writer);
map.put("content", content);
return ResponseEntity.ok(new CMRespDto<>(1, "๊ฒ์๊ธ ์์ฑ ์๋ฃ", map));
}
@PostMapping("/api/v1/dto/post") // โญ DTO๋ก ๋ฐ๊ธฐ
public ResponseEntity<?> addPost(AddPostReqDto addPostReqDto) {
log.info("{}", addPostReqDto);
return ResponseEntity.ok(new CMRespDto<>(1, "๊ฒ์๊ธ ์์ฑ ์๋ฃ", addPostReqDto));
}
@PostMapping("/api/v1/file/post") // โญ ํ์ผ(๋ช
) ๋ฐ๊ธฐ โก๏ธ formData ํํ๋ก ๋ณด๋ด์ผ ํจ.
public ResponseEntity<?> addPost2(AddPostReqDto addPostReqDto) {
log.info("{}", addPostReqDto);
List<String> fileNames = new ArrayList<String>();
String fileName1 = addPostReqDto.getFile().getOriginalFilename();
fileNames.add(fileName1);
if(addPostReqDto.getFiles() != null){
String fileName2 = addPostReqDto.getFiles().get(0).getOriginalFilename();
String fileName3 = addPostReqDto.getFiles().get(1).getOriginalFilename();
...
fileNames.add(fileName2);
fileNames.add(fileName3);
...
}
return ResponseEntity.ok(new CMRespDto<>(1, "๊ฒ์๊ธ ์์ฑ ์๋ฃ", fileNames));
}
@PostMapping("/api/v1/json/post") // โญ JSON์ผ๋ก ๋ฐ๊ธฐ โก๏ธ @RequestBody ๋ฅผ ๊ผญ ๋ฌ์์ผ ํจ.
public ResponseEntity<?> addPost3(@RequestBody AddPostReqDto addPostReqDto) {
log.info("{}", addPostReqDto);
return ResponseEntity.ok(new CMRespDto<>(1, "Json์ผ๋ก ๊ฒ์๊ธ ์์ฑ ์๋ฃ", addPostReqDto));
}
}
ํด๋ผ์ด์ธํธ์์ ์์ฒญ๋ฐ๋์ JSON ๋ฐ์ดํฐ๋ฅผ ๋ด์ ๋ณด๋ด๋ฉด @RequestBody ์ด๋ ธํ ์ด์ ์ด ํด๋น ์์ฒญ๋ฐ๋์ ๋ด๊ธด ๊ฐ์ ๊ฐ์ฒด๋ก ๋ณํ์์ผ ํ๋ผ๋ฏธํฐ ๊ฐ์ผ๋ก ๋ฐ์์ค.
โ JSON ์ ๋ณด๊ฐ @RequestBody ์ด๋
ธํ
์ด์
์ด ๋ถ์ ์ปจํธ๋กค๋ฌ๋ก ๋ณด๋ด์ง๋ฉด, Map ์ผ๋ก ์ ์ธ๋ ๋ณ์์ Json ์๋ฃํ์ ๋ฐ๋ก ๋ฐ์ ์ ์๋ค.
๐ข ์๊ฐ ๐ฑโ๐