Header Banner
GG Logo

Future Engineering

기술의 최전선을 기록합니다.

기술 자료/BackEnd/[Spring] MVC 컨트롤러와 RequestMapping

[Spring] MVC 컨트롤러와 RequestMapping

BackEnd8개월 전

※ @Controller와 @RestController는 다릅니다.

Spring MVC에서 컨트롤러는 웹 애플리케이션의 요청을 처리하고, 데이터를 준비하여 적절한 뷰에 전달하는 역할을 합니다. 컨트롤러를 통해 특정 URL과 HTTP 메서드(GET, POST 등)에 따라 요청을 처리할 수 있으며, 이를 위해 @Controller@RequestMapping 어노테이션을 사용합니다.

◎ @Controller는 뷰 템플릿을 반환하는 웹 애플리케이션

◎ @RestController는 REST API를 위한 JSON 응답

 

1. @Controller 어노테이션

  • 역할: 해당 클래스가 컨트롤러 역할을 수행함을 Spring에게 알립니다.

  • 사용 방법: 클래스 수준에서 @Controller를 사용하여, 클래스 내의 메서드들이 웹 요청을 처리하도록 설정합니다.

import org.springframework.stereotype.Controller;

@Controller
public class MyController {
    // 여기에 요청 처리 메서드를 정의합니다.
}

 

2. @RequestMapping 어노테이션

  • 역할: 특정 URL 패턴과 요청 메서드를 컨트롤러의 메서드와 매핑합니다.

  • 사용 방법: 클래스와 메서드 수준에서 사용되며, URL 패턴과 HTTP 메서드(GET, POST 등)를 매핑할 수 있습니다. 클래스 수준에서 사용된 @RequestMapping의 URL 패턴은 모든 메서드에 공통으로 적용됩니다.

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api") // 클래스 수준 매핑
public class MyController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    @ResponseBody
    public String sayHello() {
        return "Hello, Spring MVC!";
    }
}

위의 코드에서 /api/hello 경로로 들어오는 GET 요청은 sayHello 메서드에서 처리하며, Hello, Spring MVC!라는 응답을 반환합니다.

3. 세부 매핑 - @GetMapping, @PostMapping 등

Spring 4.3 이후로는 더 직관적인 매핑 어노테이션들이 제공됩니다. 따라서 아래 사용을 권장드립니다.

  • @GetMapping: GET 요청을 처리할 때 사용합니다.

  • @PostMapping: POST 요청을 처리할 때 사용합니다.

  • @PutMapping: PUT 요청을 처리할 때 사용합니다.

  • @DeleteMapping: DELETE 요청을 처리할 때 사용합니다.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/users")
public class UserController {

    @GetMapping("/profile")
    @ResponseBody
    public String getUserProfile(@RequestParam String username) {
        return "Profile of user: " + username;
    }

    @PostMapping("/create")
    @ResponseBody
    public String createUser(@RequestParam String username) {
        return "User " + username + " created successfully!";
    }
}
  • @GetMapping("/profile") 어노테이션은 /users/profile 경로로의 GET 요청을 처리하며, username이라는 요청 파라미터를 받아 사용자 프로필 정보를 반환합니다.

  • @PostMapping("/create") 어노테이션은 /users/create 경로로의 POST 요청을 처리하며, 사용자 이름을 입력 받아 새로운 사용자 생성을 나타내는 문자열을 반환합니다.

 

4. Path Variables와 Request Parameters

  • Path Variables: URL 경로에 변수를 포함시킬 수 있습니다. 예를 들어, /users/{id}와 같은 형태로 ID 값을 URL에 포함할 수 있습니다.

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

@GetMapping("/users/{id}")
@ResponseBody
public String getUserById(@PathVariable("id") int userId) {
    return "User ID: " + userId;
}

Request Parameters: @RequestParam을 사용하여 쿼리 파라미터를 받아 처리할 수 있습니다.

@GetMapping("/search")
@ResponseBody
public String searchUser(@RequestParam String name) {
    return "Search result for user: " + name;
}

5. @ResponseBody 어노테이션

  • 컨트롤러 메서드가 반환하는 데이터를 HTTP 응답 본문으로 직접 변환하여 전송합니다. 예를 들어, JSON 형태로 데이터를 반환할 때 유용합니다.

@GetMapping("/json")
@ResponseBody
public Map<String, String> getJsonResponse() {
    Map<String, String> response = new HashMap<>();
    response.put("message", "Hello, JSON!");
    return response;
}

6. 요청 매핑의 결합 예제

아래는 클래스 수준의 URL 매핑과 함께 GET 및 POST 요청을 처리하는 예제입니다.

@Controller
@RequestMapping("/products")
public class ProductController {

    @GetMapping("/{id}")
    @ResponseBody
    public String getProduct(@PathVariable int id) {
        return "Product ID: " + id;
    }

    @PostMapping("/add")
    @ResponseBody
    public String addProduct(@RequestParam String name) {
        return "Product " + name + " added successfully!";
    }
}

위 예제에서 /products 경로는 클래스 수준에서 공통으로 적용되며, 그 하위 경로에서 각각의 메서드가 GET과 POST 요청을 처리합니다.