@RequestMapping es una de las anotaciones más ampliamente utilizadas en Spring MVC. La anotación org.springframework.web.bind.annotation.RequestMapping
se utiliza para asignar solicitudes web a clases de controladores específicas y/o métodos de controladores. La anotación
@RequestMapping
se puede aplicar tanto a la clase del controlador como a los métodos. Hoy veremos varios usos de esta anotación con ejemplos y otras anotaciones como @PathVariable
y @RequestParam
.
Spring @RequestMapping
-
@RequestMapping con Clase: Podemos usarlo con la definición de clase para crear el URI base. Por ejemplo:
@Controller @RequestMapping("/home") public class HomeController { }
Ahora, /home es el URI para el cual se utilizará este controlador. Este concepto es muy similar al contexto de servlet de una aplicación web.
-
@RequestMapping con Método: Podemos usarlo con el método para proporcionar el patrón de URI para el cual se utilizará el método del controlador. Por ejemplo:
@RequestMapping(value="/method0") @ResponseBody public String method0(){ return "method0"; }
La anotación anterior también se puede escribir como
@RequestMapping("/method0")
. En una nota al margen, estoy usando @ResponseBody para enviar la respuesta de cadena para esta solicitud web, esto se hace para mantener el ejemplo simple. Como siempre hago, usaré estos métodos en una aplicación Spring MVC y los probaré con un programa o script simple. -
@RequestMapping con Múltiples URI: Podemos usar un solo método para manejar múltiples URIs, por ejemplo:
@RequestMapping(value={"/method1","/method1/second"}) @ResponseBody public String method1(){ return "method1"; }
Si observas el código fuente de la anotación RequestMapping, verás que todas sus variables son matrices. Podemos crear una matriz de cadenas para los mapeos de URI para el método del controlador.
-
@RequestMapping con Método HTTP: A veces queremos realizar operaciones diferentes según el método HTTP utilizado, incluso si la URI de la solicitud permanece igual. Podemos usar la variable de método @RequestMapping para restringir los métodos HTTP para los cuales se invocará este método. Por ejemplo:
@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"; }
-
@RequestMapping con Encabezados: Podemos especificar los encabezados que deben estar presentes para invocar el método del controlador. Por ejemplo:
@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"; }
-
@RequestMapping con Produces y Consumes: Podemos usar los encabezados
Content-Type
yAccept
para determinar el contenido de la solicitud y qué mensaje MIME desea en respuesta. Para mayor claridad, @RequestMapping proporciona variables produces y consumes donde podemos especificar el tipo de contenido de la solicitud para el cual se invocará el método y el tipo de contenido de la respuesta. Por ejemplo:@RequestMapping(value="/metodo6", produces={"application/json","application/xml"}, consumes="text/html") @ResponseBody public String metodo6(){ return "metodo6"; }
El método anterior solo puede consumir mensajes con Content-Type como text/html y puede producir mensajes de tipo application/json y application/xml.
Spring @PathVariable
-
@RequestMapping con @PathVariable: La anotación RequestMapping se puede usar para manejar URIs dinámicas donde uno o más de los valores de la URI funcionan como parámetros. Incluso podemos especificar una Expresión Regular para el parámetro dinámico de URI para aceptar solo un tipo específico de entrada. Funciona con la anotación @PathVariable a través de la cual podemos asignar la variable URI a uno de los argumentos del método. Por ejemplo:
@RequestMapping(value="/method7/{id}") @ResponseBody public String method7(@PathVariable("id") int id){ return "method7 con id="+id; } @RequestMapping(value="/method8/{id:[\\d]+}/{name}") @ResponseBody public String method8(@PathVariable("id") long id, @PathVariable("name") String name){ return "method8 con id= "+id+" y nombre="+name; }
Spring @RequestParam
- @RequestMapping con @RequestParam para parámetros de URL: A veces obtenemos parámetros en la URL de la solicitud, principalmente en solicitudes GET. Podemos usar @RequestMapping con la anotación @RequestParam para recuperar el parámetro de URL y asignarlo al argumento del método. Por ejemplo:
```
@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.
- @RequestMapping método por defecto: Si el valor está vacío para un método, funciona como método por defecto para la clase del controlador. Por ejemplo:
```
@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.
- @RequestMapping método de fallback: Podemos crear un método de fallback para la clase del controlador para asegurarnos de que estamos capturando todas las solicitudes del cliente aunque no haya métodos de manejo coincidentes. Es útil para enviar páginas de respuesta personalizadas 404 a los usuarios cuando no hay métodos de manejo para la solicitud.
```
@RequestMapping("*")
@ResponseBody
public String fallbackMethod(){
return "fallback method";
}
```
Programa de Prueba Spring RestMapping
Podemos usar Spring RestTemplate para probar los diferentes métodos anteriores, pero hoy usaré comandos cURL para probar estos métodos porque son simples y no hay muchos datos circulando. He creado un simple script de shell springTest.sh para invocar todos los métodos anteriores e imprimir su salida. Se ve así:
#!/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";
Nótese que he desplegado mi aplicación web en Tomcat-7 y está ejecutándose en el puerto 9090. SpringRequestMappingExample es el contexto del servlet de la aplicación. Ahora, cuando ejecuto este script a través de la línea de comandos, obtengo la siguiente salida.
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$
La mayoría de estos son autoexplicativos, aunque quizás quieras revisar los métodos predeterminados y de respaldo. Eso es todo para Ejemplo de Spring RequestMapping, espero que te ayude a entender esta anotación y sus diversas características. Deberías descargar el proyecto de ejemplo desde el siguiente enlace y probar diferentes escenarios para explorarlo más a fondo.