@PostMapping

Yuno·2024년 8월 18일
0

Spring Framework 에서 사용되는 어노테이션으로, HTTP POST 요청을 처리하는 메서드를 지정하는 데 사용됨. Spring MVC의 컨트롤러에서 주로 사용됨.
이 어노테이션은 @RequestMapping 의 축약형으로, method = RequestMethod.POST 를 설정하는 것과 같음


👉 기본 사용

간단한 POST 요청을 처리하는 컨트롤러 메서드

@RestController
@RequestMapping("/api")
public class MyController {
	
    @PostMapping("/submit")
    public ResponseEntity<String> handlePostRequest(@RequestBody MyRequest request) {
    	// 요청 본문에서 MyRequest 객체를 추출
        // 요청 처리 로직 구현
        return ResponseEntity.ok("Request received");
    }
}
  • @RestController 는 이 클래스가 RESTful 웹 서비스의 컨트롤러임을 나타냄
  • @RequestMapping("/api") 는 클래스 수준의 URL 패턴을 설정
  • @PostMapping("/submit")/api/submit URL로 들어오는 POST 요청을 처리함
  • @RequestBody 는 요청 본문을 MyRequest 객체로 변환함

👉 폼 데이터 처리

폼 데이터 전송을 처리할 수도 있음. 예를 들어, 폼 데이터가 application/x-www-form-urlencoded 형식으로 전송되면

@RestController
@RequestMapping("/api")
public class MyController("/api")
public class MyController {
	
    @PostMapping("/submitForm")
    public ResponseEntity<String> handleFormSubmit(@RequestParam String name, @RequestParam int age) {
    	// 폼 데이터 처리
        return ResponseEntity.ok("Form submitted with name: " + name + "and age: " + age);
    }
}

@RequestParam 은 쿼리 파라미터 또는 폼 데이터를 메서드 매개변수로 매핑함


👉 파일 업로드

@RestController
@RequestMapping("/api")
public class MyController {
	
    @PostMapping("/upload")
    public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
    	// 파일 처리 로직
        return ResponseEntity.ok("File uploaded successfully: " + file.getOriginalFilename());
    }
}
  • @RequestParam("file") 은 파일 업로드를 처리
  • MultipartFile 은 Spring의 파일 업로드 지원을 위한 클래스

👉 JSON 데이터 처리

클라이언트가 JSON 데이터를 전송하는 경우, @RequestBody 를 사용하여 JSON을 자바 객체로 변환할 수 있음.

@RestController
@RequestMapping("/api")
public class MyController

	@PostMapping("/processJson")
    public ResponseEntity<String> processJson(@RequestBody MyJsonData) {
    	// JSON 데이터 처리
        return ResponseEntity.ok("Received JSON data with value: " + data.getValue());
    }
  • @RequestBody 는 JSON 데이터를 MyJsonData 객체로 변환함
profile
Hello World

0개의 댓글