1. Panoramica
Per semplificare lo sviluppo dei servizi web REST e dei loro client in Java, è stata progettata un'implementazione standard e portabile dell'API JAX-RS chiamata Jersey.
Jersey è un framework open source per lo sviluppo di servizi Web REST che forniscono supporto per API JAX-RS e funge da implementazione di riferimento JAX-RS .
In questo tutorial vedremo come impostare un corpo di risposta Jersey con diversi tipi di media.
2. Dipendenze di Maven
Innanzitutto, abbiamo bisogno delle seguenti dipendenze incluse nel file pom.xml :
org.glassfish.jersey.bundles jaxrs-ri 2.26 org.glassfish.jersey.core jersey-server 2.26
L'ultima versione di JAX-RS può essere trovata su jaxrs-ri e il server Jersey può essere trovato su jersey-server
3. Risposta in Jersey
Naturalmente, ci sono diversi modi per costruire una risposta usando Jersey e vedremo come costruirli di seguito.
Tutti gli esempi qui sono richieste HTTP GET e useremo il comando curl per testare le risorse.
3.1. Ok risposta di testo
L'endpoint mostrato qui è un semplice esempio di come il testo normale può essere restituito come risposta Jersey:
@GET @Path("/ok") public Response getOkResponse() { String message = "This is a text response"; return Response .status(Response.Status.OK) .entity(message) .build(); }
Possiamo eseguire un HTTP GET usando curl per verificare la risposta:
curl -XGET //localhost:8080/jersey/response/ok
Questo endpoint invierà una risposta come segue:
This is a text response
Quando il tipo di supporto non è specificato, Jersey verrà impostato automaticamente su text / plain.
3.2. Risposta di errore
Gli errori possono anche essere restituiti come risposta Jersey:
@GET @Path("/not_ok") public Response getNOkTextResponse() { String message = "There was an internal server error"; return Response .status(Response.Status.INTERNAL_SERVER_ERROR) .entity(message) .build(); }
Per verificare la risposta, possiamo eseguire una richiesta HTTP GET utilizzando curl :
curl -XGET //localhost:8080/jersey/response/not_ok
Il messaggio di errore verrà restituito nella risposta:
There was an internal server error
3.3. Risposta in testo normale
Possiamo anche restituire semplici risposte in testo normale :
@GET @Path("/text_plain") public Response getTextResponseTypeDefined() { String message = "This is a plain text response"; return Response .status(Response.Status.OK) .entity(message) .type(MediaType.TEXT_PLAIN) .build(); }
Di nuovo, possiamo eseguire un HTTP GET usando curl per verificare la risposta:
curl -XGET //localhost:8080/jersey/response/text_plain
La risposta sarà la seguente:
This is a plain text response
Lo stesso risultato potrebbe essere ottenuto anche tramite l' annotazione Produces invece di utilizzare il metodo type () nella risposta :
@GET @Path("/text_plain_annotation") @Produces({ MediaType.TEXT_PLAIN }) public Response getTextResponseTypeAnnotated() { String message = "This is a plain text response via annotation"; return Response .status(Response.Status.OK) .entity(message) .build(); }
Possiamo eseguire la verifica della risposta utilizzando curl :
curl -XGET //localhost:8080/jersey/response/text_plain_annotation
Ecco la risposta:
This is a plain text response via annotation
3.4. Risposta JSON utilizzando POJO
È anche possibile utilizzare un semplice Plain Old Java Object (POJO) per creare una risposta Jersey .
Abbiamo un POJO Persona molto semplice mostrato di seguito, che useremo per costruire una risposta:
public class Person { String name; String address; // standard constructor // standard getters and setters }
Il POJO della persona può ora essere utilizzato per restituire JSON come corpo della risposta :
@GET @Path("/pojo") public Response getPojoResponse() { Person person = new Person("Abhinayak", "Nepal"); return Response .status(Response.Status.OK) .entity(person) .build(); }
Il funzionamento di questo endpoint GET può essere verificato - tramite il seguente comando curl :
curl -XGET //localhost:8080/jersey/response/pojo
Il POJO della persona verrà trasformato in un JSON e restituito come risposta:
{"address":"Nepal","name":"Abhinayak"}
3.5. Risposta JSON utilizzando una stringa semplice
Possiamo usare stringhe preformattate per creare una risposta e può essere fatto semplicemente.
Il seguente endpoint è un esempio di come un JSON rappresentato come stringa può essere restituito come JSON nella risposta Jersey:
@GET @Path("/json") public Response getJsonResponse() { String message = "{\"hello\": \"This is a JSON response\"}"; return Response .status(Response.Status.OK) .entity(message) .type(MediaType.APPLICATION_JSON) .build(); }
This can be verified by doing an HTTP GET using curl to verify the response:
curl -XGET //localhost:8080/jersey/response/json
Calling this resource will return a JSON:
{"hello":"This is a JSON response"}
The same pattern applies for other common media types like XML or HTML. We just need to notify Jersey that it's an XML or HTML using MediaType.TEXT_XML or MediaType.TEXT_HTML and Jersey will handle the rest.
4. Conclusion
In this quick article, we constructed Jersey (JAX-RS) responses for a variety of media types.
All of the code snippets, mentioned in the article, can be found in over on GitHub.