Esempio di annotazione @RequestMapping di Spring MVC con Controller, Metodi, Intestazioni, Parametri, @RequestParam, @PathVariable

@RequestMapping è una delle annotazioni più ampiamente utilizzate di Spring MVC. L’annotazione org.springframework.web.bind.annotation.RequestMapping viene utilizzata per mappare le richieste web su classi handler specifiche e/o metodi handler. @RequestMapping può essere applicato sia alla classe del controller che ai metodi. Oggi esamineremo vari utilizzi di questa annotazione con esempi e altre annotazioni come @PathVariable e @RequestParam.

Spring @RequestMapping

  1. @RequestMapping con la Classe: Possiamo utilizzarla con la definizione della classe per creare l’URI di base. Ad esempio:

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

    Ora /home è l’URI per il quale questo controller sarà utilizzato. Questo concetto è molto simile al contesto del servlet di un’applicazione web.

  2. @RequestMapping con il Metodo: Possiamo usarlo con il metodo per fornire il modello di URI per cui verrà utilizzato il metodo del gestore. Ad esempio:

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

    L’annotazione sopra può anche essere scritta come @RequestMapping("/method0"). Come nota laterale, sto utilizzando @ResponseBody per inviare la risposta String per questa richiesta web, ciò è fatto per mantenere l’esempio semplice. Come faccio sempre, utilizzerò questi metodi in un’applicazione Spring MVC e li testerò con un programma o uno script semplice.

  3. @RequestMapping con più URI: Possiamo utilizzare un unico metodo per gestire più URI, ad esempio:

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

    Se guarderai il codice sorgente dell’annotazione RequestMapping, vedrai che tutte le sue variabili sono array. Possiamo creare un array di stringhe per i mapping URI per il metodo del gestore.

  4. @RequestMapping con Metodo HTTP: A volte vogliamo eseguire operazioni diverse in base al metodo HTTP utilizzato, anche se l’URI della richiesta rimane lo stesso. Possiamo utilizzare la variabile del metodo @RequestMapping per limitare i metodi HTTP per i quali verrà invocato questo metodo. Ad esempio:

    @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 con Intestazioni: Possiamo specificare le intestazioni che devono essere presenti per invocare il metodo gestore. Ad esempio:

    @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 con Produces e Consumes: Possiamo utilizzare l’intestazione Content-Type e Accept per scoprire i contenuti della richiesta e quale messaggio mime si desidera in risposta. Per chiarezza, @RequestMapping fornisce le variabili produces e consumes dove possiamo specificare il tipo di contenuto della richiesta per il quale verrà invocato il metodo e il tipo di contenuto della risposta. Ad esempio:

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

    Il metodo sopra può consumare solo messaggi con Content-Type come text/html e è in grado di produrre messaggi di tipo application/json e application/xml.

Spring @PathVariable

  1. @RequestMapping con @PathVariable: L’annotazione RequestMapping può essere utilizzata per gestire URI dinamici in cui uno o più dei valori dell’URI funzionano come parametri. Possiamo anche specificare Espressioni Regolari per il parametro dinamico dell’URI per accettare solo un tipo specifico di input. Funziona con l’annotazione @PathVariable attraverso la quale possiamo mappare la variabile URI a uno degli argomenti del metodo. Ad esempio:

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

Spring @RequestParam

  1. @RequestMapping con @RequestParam per i parametri dell’URL: A volte otteniamo parametri nell’URL della richiesta, principalmente nelle richieste GET. Possiamo utilizzare @RequestMapping con @RequestParam annotazione per recuperare il parametro dell’URL e mapparlo all’argomento del metodo. Ad esempio:
```
@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 metodo predefinito: Se il valore è vuoto per un metodo, funziona come metodo predefinito per la classe del controller. Per esempio:
```
@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 metodo di fallback: Possiamo creare un metodo di fallback per la classe del controller per assicurarci di catturare tutte le richieste dei client anche se non ci sono metodi handler corrispondenti. È utile nell’invio di pagine di risposta personalizzate 404 agli utenti quando non ci sono metodi handler per la richiesta.
```
@RequestMapping("*")
@ResponseBody
public String fallbackMethod(){
	return "fallback method";
}
```

Programma di test Spring RestMapping

Possiamo usare Spring RestTemplate per testare i diversi metodi sopra, ma oggi utilizzerò comandi cURL per testare questi metodi perché sono semplici e non c’è molto flusso di dati. Ho creato uno script shell semplice springTest.sh per invocare tutti i metodi sopra e stampare il loro output. Sembra così:

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

Nota che ho distribuito la mia applicazione web su Tomcat-7 e sta funzionando sulla porta 9090. SpringRequestMappingExample è il contesto del servlet dell’applicazione. Ora quando eseguo questo script tramite la riga di comando, ottengo il seguente output.

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 maggior parte di questi sono autoesplicativi, anche se potresti voler controllare i metodi predefiniti e di fallback. Questo è tutto per Esempio di Spring RequestMapping, spero che ti aiuterà a capire questa annotazione e le sue varie caratteristiche. Dovresti scaricare il progetto di esempio dal link sottostante e provare scenari diversi per esplorarlo ulteriormente.

Scarica il progetto Spring MVC RequestMapping

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