@GetMapping, @PostMapping, @PutMapping, @DeleteMapping

2024. 5. 23. 09:46Back-End/Spring

@GetMapping

@GetMapping은 HTTP GET 요청을 처리하는 메서드에 사용된다. 주로 리소스를 읽어오거나 조회할 때 사용된다.

 

Controller 코드

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class ExampleController {

    @GetMapping("/greeting")
    public String greeting(@RequestParam(name = "name", required = false, defaultValue = "World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
}
 

greeting.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Greeting</title>
</head>
<body>
<h1>Hello, <span th:text="${name}"></span>!</h1>
</body>
</html>

 

결과

  • URL: http://localhost:8080/greeting?name=John
  • 화면에 "Hello, John!" 이 출력된다.
  • URL: http://localhost:8080/greeting
  • 화면에 "Hello, World!" 이 출력된다.

@PostMapping

@PostMapping은 HTTP POST 요청을 처리하는 메서드에 사용된다. 주로 데이터를 서버로 전송하여 리소스를 생성하거나 업데이트할 때 사용된다.

Controller 코드

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.ui.Model;

@Controller
public class FormController {

    @PostMapping("/submitForm")
    public String submitForm(@ModelAttribute FormData formData, Model model) {
        model.addAttribute("formData", formData);
        return "result";
    }
}

 

FormData 클래스

public class FormData {
    private String name;
    private String email;

    // Getters and Setters
}

 

form.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Form</title>
</head>
<body>
<form action="/submitForm" method="post">
    Name: <input type="text" name="name"><br>
    Email: <input type="text" name="email"><br>
    <input type="submit" value="Submit">
</form>
</body>
</html>

 

result.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Result</title>
</head>
<body>
<h1>Form Data</h1>
<p>Name: <span th:text="${formData.name}"></span></p>
<p>Email: <span th:text="${formData.email}"></span></p>
</body>
</html>

 

결과

  • 폼을 제출하면 결과 페이지에 입력한 이름과 이메일이 출력된다.

@PutMapping

Controller 코드

import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UpdateController {

    @PutMapping("/update/{id}")
    public String updateResource(@PathVariable("id") Long id, @RequestBody ResourceData resourceData) {
        // 여기서 리소스를 업데이트하는 로직이 있다
        return "Resource with ID " + id + " updated to " + resourceData.getData();
    }
}

 

ResourceData 클래스

public class ResourceData {
    private String data;

    // Getters and Setters
}
 
 

결과

  • PUT 요청을 통해 JSON 데이터를 전송하면, 리소스가 업데이트되었다는 메시지를 반환한다.
  • 예제:
    • 요청: PUT http://localhost:8080/update/1
    • 본문: {"data": "new data"}
    • 응답: Resource with ID 1 updated to new data

@DeleteMapping

Controller 코드

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DeleteController {

    @DeleteMapping("/delete/{id}")
    public String deleteResource(@PathVariable("id") Long id) {
        // 여기서 리소스를 삭제하는 로직이 있다
        return "Resource with ID " + id + " deleted";
    }
}

결과

  • DELETE 요청을 통해 특정 ID의 리소스를 삭제한다는 메시지를 반환한다.
  • 예제:
    • 요청: DELETE http://localhost:8080/delete/1
    • 응답: Resource with ID 1 deleted

결론

Spring MVC에서 @GetMapping, @PostMapping, @PutMapping, @DeleteMapping을 사용하면 각 HTTP 메서드에 대해 명확하고 간결하게 매핑할 수 있다. 이를 통해 RESTful API를 쉽게 구현할 수 있으며, 각 매핑 어노테이션을 적절히 사용하여 다양한 요청을 효과적으로 처리할 수 있다.