Exemplo de Anotação @RequestMapping do Spring MVC com Controller, Métodos, Cabeçalhos, Parâmetros, @RequestParam, @PathVariable

@RequestMapping é uma das anotações mais amplamente utilizadas do Spring MVC. A anotação org.springframework.web.bind.annotation.RequestMapping é usada para mapear solicitações da web para classes de manipulador específicas e/ou métodos de manipulador. @RequestMapping pode ser aplicado à classe do controlador, bem como aos métodos. Hoje vamos analisar vários usos desta anotação com exemplos e outras anotações como @PathVariable e @RequestParam.

Spring @RequestMapping

  1. @RequestMapping com Classe: Podemos usá-lo com a definição de classe para criar o URI base. Por exemplo:

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

    Agora /home é o URI para o qual este controlador será usado. Este conceito é muito semelhante ao contexto do servlet de uma aplicação web.

  2. @RequestMapping com Método: Podemos usá-lo com o método para fornecer o padrão URI para o qual o método do manipulador será usado. Por exemplo:

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

    Essa anotação acima também pode ser escrita como @RequestMapping("/method0"). Em um nota lateral, estou usando @ResponseBody para enviar a resposta de String para essa solicitação web, isso é feito para manter o exemplo simples. Como sempre faço, vou usar esses métodos em uma aplicação Spring MVC e testá-los com um programa ou script simples.

  3. @RequestMapping com Múltiplos URI: Podemos usar um único método para lidar com vários URIs, por exemplo:

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

    Se você olhar o código-fonte da anotação RequestMapping, verá que todas as suas variáveis são arrays. Podemos criar um array de Strings para os mapeamentos de URI para o método do manipulador.

  4. @RequestMapping com Método HTTP: Às vezes, queremos realizar operações diferentes com base no método HTTP utilizado, mesmo que o URI da solicitação permaneça o mesmo. Podemos usar a variável de método @RequestMapping para restringir os métodos HTTP para os quais esse método será invocado. Por exemplo:

    @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 com Cabeçalhos: Podemos especificar os cabeçalhos que devem estar presentes para invocar o método manipulador. Por exemplo:

    @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 com Produz e Consome: Podemos usar o cabeçalho Content-Type e Accept para descobrir os conteúdos da solicitação e qual é a mensagem mime desejada na resposta. Para clareza, @RequestMapping fornece as variáveis produces e consumes onde podemos especificar o tipo de conteúdo da solicitação para o qual o método será invocado e o tipo de conteúdo da resposta. Por exemplo:

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

    O método acima pode consumir mensagem apenas com Content-Type como text/html e é capaz de produzir mensagens do tipo application/json e application/xml.

Spring @PathVariable

  1. @RequestMapping com @PathVariable: A anotação RequestMapping pode ser usada para lidar com URIs dinâmicos, onde um ou mais dos valores da URI funcionam como parâmetro. Podemos até mesmo especificar uma Expressão Regular para o parâmetro dinâmico da URI, a fim de aceitar apenas um tipo específico de entrada. Funciona com a anotação @PathVariable, através da qual podemos mapear a variável da URI para um dos argumentos do método. Por exemplo:

    @RequestMapping(value="/metodo7/{id}")
    @ResponseBody
    public String metodo7(@PathVariable("id") int id){
        return "metodo7 com id="+id;
    }
    
    @RequestMapping(value="/metodo8/{id:[\\d]+}/{nome}")
    @ResponseBody
    public String metodo8(@PathVariable("id") long id, @PathVariable("nome") String nome){
        return "metodo8 com id= "+id+" e nome="+nome;
    }
    

Spring @RequestParam

  1. @RequestMapping com @RequestParam para parâmetros de URL: Às vezes obtemos parâmetros na URL da requisição, principalmente em requisições GET. Podemos usar @RequestMapping com a anotação @RequestParam para recuperar o parâmetro da URL e mapeá-lo para o argumento do método. Por exemplo:
```
@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 método padrão: Se o valor estiver vazio para um método, ele funciona como método padrão para a classe controladora. Por exemplo:
```
@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 método de fallback: Podemos criar um método de fallback para a classe controladora para garantir que estamos capturando todas as solicitações do cliente, mesmo que não haja métodos de manipulador correspondentes. É útil enviar páginas de resposta 404 personalizadas aos usuários quando não houver métodos de manipulador para a solicitação.
```
@RequestMapping("*")
@ResponseBody
public String fallbackMethod(){
	return "fallback method";
}
```

Programa de Teste Spring RestMapping

Podemos usar Spring RestTemplate para testar os diferentes métodos acima, mas hoje vou usar comandos cURL para testar esses métodos porque são simples e não há muitos dados fluindo. Eu criei um script shell simples springTest.sh para invocar todos os métodos acima e imprimir sua saída. Parece o seguinte.

#!/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";

Observe que eu implantei minha aplicação web no Tomcat-7 e ela está em execução na porta 9090. SpringRequestMappingExample é o contexto do servlet da aplicação. Agora, quando eu executo este script através da linha de comando, obtenho a seguinte saída.

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$ 

A maioria destes são autoentendidos, embora você possa querer verificar métodos padrão e de fallback. Isso é tudo para o exemplo de Mapeamento de Solicitações Spring, espero que ajude você a entender esta anotação e suas várias funcionalidades. Você deve baixar o projeto de exemplo no link abaixo e tentar diferentes cenários para explorá-lo mais a fundo.

Baixe o Projeto de Mapeamento de Solicitações Spring MVC

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