Les paramètres complexes dans les corps de requêtes
Jakarta REST facilite la manipulation des données complexes en automatisant la conversion entre les formats d’échange (JSON, XML) et les objets Java. Cette conversion bidirectionnelle s’applique particulièrement aux corps des requêtes HTTP (PUT, POST), où les données reçues sont automatiquement transformées en paramètres Java utilisables dans vos méthodes.
L’annotation @Consumes joue un rôle central dans ce processus en spécifiant les types MIME acceptés par votre endpoint. Par exemple, dans la méthode addAuthor(), elle indique les formats acceptables pour la création d’un auteur. Le client précise le format effectivement utilisé via l’en-tête HTTP Content-Type, et le serveur retourne l’entité complète, y compris les champs générés comme l’ID.
Les exemples suivants sont accessibles dans le dépôt :
/*** Adds an new author to the data.* Status annotation is a trick to fine tune 2XX status codes (see the status package).**@paramauthorThe author to be added without its id.*@return The added author with its id.*@throwsIllegalArgumentExceptionif the author has an explicit id (id!=0).*/@POST@Status(Status.CREATED)@Consumes(MediaType.APPLICATION_JSON)public Library.AuthoraddAuthor(Library.Author author)throws BusinessException {return Library.demoLibrary.addAuthor(author);}
Adds an author :
La méthode updateAuteur est appelée par un PUT mais avec une resource précise (indiquée dans l’URL) à mettre à jour.
/*** Update an author with an given id.**@paramidthe id injected from the path param "id"*@paramauthora injected author made from the JSON data (@Consumes) from body of the request. This author is forbidden to havce an Id.*@return The resulting author with its id.*@throwsNotFoundExceptionis returned if no author has the "id".*@throwsIllegalArgumentExceptionis returned if an "id" is also given in the request body.*/@PUT@Path("{id}")@Consumes(MediaType.APPLICATION_JSON)public Library.AuthorupdateAuthor(@PathParam("id")long id, Library.Author author)throws BusinessException {return Library.demoLibrary.updateAuteur(id, author);}
Fully update an author
La suppression
La suppression des ressources se fait avec les approches précédentes.
/*** Removes an author by id from the data.**@paramidthe id of the author to remove*@throwsNotFoundExceptionis returned if no author has the "id".*/@DELETE@Path("{id}")publicvoidremoveAuthor(@PathParam("id")finallong id)throws BusinessException { Library.demoLibrary.removeAuthor(id);}
Removes one author :
/*** Removes every authors*/@DELETEpublicvoidremoveAuthors(){ Library.demoLibrary.removesAuthors();}