웹사이트 검색

컨트롤러, 메소드, 헤더, 매개변수, @RequestParam, @PathVariable이 포함된 Spring MVC @RequestMapping 주석 예제


스프링 @RequestMapping

  1. @RequestMapping with Class: We can use it with class definition to create the base URI. For example:

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

    Now /home is the URI for which this controller will be used. This concept is very similar to servlet context of a web application.

  2. @RequestMapping with Method: We can use it with method to provide the URI pattern for which handler method will be used. For example:

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

    Above annotation can also be written as @RequestMapping("/method0"). On a side note, I am using @ResponseBody to send the String response for this web request, this is done to keep the example simple. Like I always do, I will use these methods in Spring MVC application and test them with a simple program or script.

  3. @RequestMapping with Multiple URI: We can use a single method for handling multiple URIs, for example:

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

    If you will look at the source code of RequestMapping annotation, you will see that all of it’s variables are arrays. We can create String array for the URI mappings for the handler method.

  4. @RequestMapping method variable to narrow down the HTTP methods for which this method will be invoked. For example:

    @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: We can specify the headers that should be present to invoke the handler method. For example:

    @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 provides produces and consumes variables where we can specify the request content-type for which method will be invoked and the response content type. For example:

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

    Above method can consume message only with Content-Type as text/html and is able to produce messages of type application/json and application/xml.

스프링 @PathVariable

  1. @PathVariable annotation through which we can map the URI variable to one of the method arguments. For example:

    @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;
    }
    

스프링 @RequestParam

  1. URL 매개변수를 검색하고 메소드 인수에 맵핑하기 위한 @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 테스트 프로그램

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 프로젝트 다운로드


판권 소유. © Linux-Console.net • 2019-2024