Spring MVC @RequestMapping 주석 예시 및 컨트롤러, 메서드, 헤더, 매개변수, @RequestParam, @PathVariable

@RequestMapping은 가장 널리 사용되는 Spring MVC 어노테이션 중 하나입니다. org.springframework.web.bind.annotation.RequestMapping 어노테이션은 웹 요청을 특정 핸들러 클래스 및/또는 핸들러 메서드에 매핑하는 데 사용됩니다. @RequestMapping은 컨트롤러 클래스 및 메서드에 모두 적용될 수 있습니다. 오늘은 이 어노테이션의 다양한 사용 방법과 예제, 그리고 다른 어노테이션인 @PathVariable@RequestParam에 대해 살펴보겠습니다.

Spring @RequestMapping

  1. @RequestMapping을 사용한 클래스: 클래스 정의와 함께 사용하여 기본 URI를 생성할 수 있습니다. 예를 들면:

    @Controller
    @RequestMapping("/home")
    public class HomeController {
    
    }
    

    이제 /home은 이 컨트롤러가 사용될 URI입니다. 이 개념은 웹 애플리케이션의 서블릿 컨텍스트와 매우 유사합니다.

  2. @RequestMapping와 메서드와 함께: 메서드와 함께 사용하여 핸들러 메서드가 사용될 URI 패턴을 제공할 수 있습니다. 예를 들어:

    @RequestMapping(value="/method0")
    @ResponseBody
    public String method0(){
    	return "method0";
    }
    

    위의 주석은 @RequestMapping("/method0")으로도 작성할 수 있습니다. 부연 설명으로, 나는 이 웹 요청에 대한 문자열 응답을 보내기 위해 @ResponseBody를 사용하고 있습니다. 이 예제를 간단하게 유지하기 위해 이렇게 합니다. 항상처럼, 나는 Spring MVC 애플리케이션에서 이러한 방법을 사용하고 간단한 프로그램이나 스크립트로 테스트할 것입니다.

  3. 다중 URI를 사용한 @RequestMapping: 하나의 메서드로 여러 URI를 처리할 수 있습니다. 예를 들어 다음과 같습니다.

    @RequestMapping(value={"/method1","/method1/second"})
    @ResponseBody
    public String method1(){
    	return "method1";
    }
    

    RequestMapping 어노테이션의 소스 코드를 살펴보면 그 모든 변수가 배열임을 알 수 있습니다. Handler 메서드의 URI 매핑을 위한 String 배열을 생성할 수 있습니다.

  4. @RequestMapping with HTTP Method: 때로는 요청 URI가 동일한 상태에서도 사용된 HTTP 메소드에 따라 다른 작업을 수행하려고 합니다. 이 메소드가 호출될 HTTP 메소드를 좁히기 위해 @RequestMapping 메소드 변수를 사용할 수 있습니다. 예를 들어:

    @RequestMapping(value="/method2", method=RequestMethod.POST)
    @ResponseBody
    public String method2(){
    	return "method2";
    }
    	
    @RequestMapping(value="/method3", method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String method3(){
    	return "method3";
    }
    
  5. @RequestMapping with Headers: 핸들러 메소드를 호출하려면 존재해야 하는 헤더를 지정할 수 있습니다. 예를 들어:

    @RequestMapping(value="/method4", headers="name=pankaj")
    @ResponseBody
    public String method4(){
    	return "method4";
    }
    	
    @RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})
    @ResponseBody
    public String method5(){
    	return "method5";
    }
    
  6. @RequestMapping with Produces and Consumes: 요청 콘텐츠를 찾고 응답으로 원하는 MIME 메시지를 확인하기 위해 헤더 Content-TypeAccept을 사용할 수 있습니다. 명확성을 위해 @RequestMappingproducesconsumes 변수를 제공하며 메서드가 호출될 요청 콘텐츠 유형과 응답 콘텐츠 유형을 지정할 수 있습니다. 예를 들어:

    @RequestMapping(value="/method6", produces={"application/json","application/xml"}, consumes="text/html")
    @ResponseBody
    public String method6(){
    	return "method6";
    }
    

    위의 메서드는 Content-Type이 text/html인 메시지만 수락하고 application/jsonapplication/xml 유형의 메시지를 생성할 수 있습니다.

스프링 @PathVariable

  1. @RequestMapping@PathVariable: RequestMapping 어노테이션은 하나 이상의 URI 값이 매개변수로 작동하는 동적 URIs를 처리하는 데 사용할 수 있습니다. 심지어 URI 동적 매개변수에 대해 정규 표현식을 지정할 수도 있습니다. 이것은 @PathVariable 어노테이션과 함께 작동하여 URI 변수를 메서드 인수 중 하나에 매핑할 수 있습니다. 예를 들어:

    @RequestMapping(value="/method7/{id}")
    @ResponseBody
    public String method7(@PathVariable("id") int id){
    	return "method7 with id="+id;
    }
    	
    @RequestMapping(value="/method8/{id:[\\d]+}/{name}")
    @ResponseBody
    public String method8(@PathVariable("id") long id, @PathVariable("name") String name){
    	return "method8 with id= "+id+" and name="+name;
    }
    

Spring @RequestParam

  1. @RequestParam와 함께 @RequestMapping을 사용하여 URL 매개변수를 얻을 수 있습니다.: 때로는 요청 URL에서 매개변수를 받습니다. 대부분은 GET 요청에서 발생합니다. URL 매개변수를 검색하고 메서드 인수로 매핑하는 데 @RequestMapping@RequestParam 주석을 사용할 수 있습니다. 예를 들어:
```
@RequestMapping(value="/method9")
@ResponseBody
public String method9(@RequestParam("id") int id){
	return "method9 with id= "+id;
}
```

For this method to work, the parameter name should be "id" and it should be of type int.
  1. @RequestMapping 기본 메서드: 메서드에 대한 값이 비어 있으면 컨트롤러 클래스의 기본 메서드로 작동합니다. 예를 들어:
```
@RequestMapping()
@ResponseBody
public String defaultMethod(){
	return "default method";
}
```

As you have seen above that we have mapped `/home` to `HomeController`, this method will be used for the default URI requests.
  1. @RequestMapping 후속 메서드: 일치하는 핸들러 메서드가 없어도 모든 클라이언트 요청을 캐치하기 위해 컨트롤러 클래스에 후속 메서드를 생성할 수 있습니다. 요청에 대한 핸들러 메서드가 없을 때 사용자에게 사용자 정의 404 응답 페이지를 보내는 데 유용합니다.
```
@RequestMapping("*")
@ResponseBody
public String fallbackMethod(){
	return "fallback method";
}
```

Spring RestMapping 테스트 프로그램

위의 다른 메서드를 테스트하기 위해 Spring RestTemplate을 사용할 수 있지만, 오늘은 이러한 메서드를 테스트하기 위해 cURL 명령을 사용할 것입니다. 이 명령은 간단하고 데이터가 많이 흐르지 않기 때문입니다. 모든 위의 메서드를 호출하고 결과를 출력하기 위해 간단한 셸 스크립트 springTest.sh를 작성했습니다. 다음과 같이 보입니다.

#!/bin/bash

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method0";
curl https://localhost:9090/SpringRequestMappingExample/home/method0;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home";
curl https://localhost:9090/SpringRequestMappingExample/home;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/xyz";
curl https://localhost:9090/SpringRequestMappingExample/home/xyz;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method1";
curl https://localhost:9090/SpringRequestMappingExample/home/method1;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method1/second";
curl https://localhost:9090/SpringRequestMappingExample/home/method1/second;
printf "\n\n*****\n\n";

echo "curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2";
curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2;
printf "\n\n*****\n\n";

echo "curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3";
curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3;
printf "\n\n*****\n\n";

echo "curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3";
curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3;
printf "\n\n*****\n\n";

echo "curl -H "name:pankaj" https://localhost:9090/SpringRequestMappingExample/home/method4";
curl -H "name:pankaj" https://localhost:9090/SpringRequestMappingExample/home/method4;
printf "\n\n*****\n\n";

echo "curl -H "name:pankaj" -H "id:1" https://localhost:9090/SpringRequestMappingExample/home/method5";
curl -H "name:pankaj" -H "id:1" https://localhost:9090/SpringRequestMappingExample/home/method5;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method6";
curl https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" -H "Accept:application/json" -i https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" -H "Accept:application/json" -i https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" -H "Accept:application/xml" -i https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" -H "Accept:application/xml" -i https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method7/1";
curl https://localhost:9090/SpringRequestMappingExample/home/method7/1;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa";
curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20";
curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20;
printf "\n\n*****DONE*****\n\n";

웹 애플리케이션을 Tomcat-7에 배포했으며 포트 9090에서 실행 중임을 유의하십시오. SpringRequestMappingExample은 응용 프로그램의 서블릿 컨텍스트입니다. 이 스크립트를 명령 줄을 통해 실행하면 다음 출력이 표시됩니다.

pankaj:~ pankaj$ ./springTest.sh 
curl https://localhost:9090/SpringRequestMappingExample/home/method0
method0

*****

curl https://localhost:9090/SpringRequestMappingExample/home
default method

*****

curl https://localhost:9090/SpringRequestMappingExample/home/xyz
fallback method

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method1
method1

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method1/second
method1

*****

curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2
method2

*****

curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3
method3

*****

curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3
method3

*****

curl -H name:pankaj https://localhost:9090/SpringRequestMappingExample/home/method4
method4

*****

curl -H name:pankaj -H id:1 https://localhost:9090/SpringRequestMappingExample/home/method5
method5

*****

curl -H Content-Type:text/html https://localhost:9090/SpringRequestMappingExample/home/method6
method6

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method6
fallback method

*****

curl -H Content-Type:text/html -H Accept:application/json -i https://localhost:9090/SpringRequestMappingExample/home/method6
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Content-Length: 7
Date: Thu, 03 Jul 2014 18:14:10 GMT

method6

*****

curl -H Content-Type:text/html -H Accept:application/xml -i https://localhost:9090/SpringRequestMappingExample/home/method6
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/xml
Content-Length: 7
Date: Thu, 03 Jul 2014 18:14:10 GMT

method6

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method7/1
method7 with id=1

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa
method8 with id= 10 and name=Lisa

*****

curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20
method9 with id= 20

*****DONE*****

pankaj:~ pankaj$ 

대부분은 스스로 이해됩니다만 기본 및 대체 방법을 확인해 볼 수 있습니다. 이것으로 Spring RequestMapping 예제는 여러분이 이 주석과 그 다양한 기능을 이해하는 데 도움이 될 것을 바랍니다. 아래 링크에서 샘플 프로젝트를 다운로드하고 다양한 시나리오를 시도하여 더 자세히 알아보십시오.

Spring MVC RequestMapping 프로젝트 다운로드

Source:
https://www.digitalocean.com/community/tutorials/spring-requestmapping-requestparam-pathvariable-example