users@jersey.java.net

RE:POSTing JSON to Resource from HTML

From: David Sells <dsells_at_gmail.com>
Date: Thu, 20 Aug 2009 07:53:02 -0400

Thanks Paul,

I got it working in the end. The problem was actually in using
Prototype.js, writing my own AJAX call proved to be considerably
easier. I did make the
change to a void return and did have to deal with the 204 rather than the 200.

I also found this blog very useful from Jakub Podlesak:
http://blogs.sun.com/enterprisetechtips/entry/consuming_restful_web_services_with

Thanks,
David



On Aug 19, 2009, at 10:05 PM, David Sells wrote:

> Hi Everyone,
>
> I have a general question with respect to the JAXB-JSON conversion
> that takes place both inbound and outbound from resources.
>
> On the outbound side every thing works well:
> @GET
> @Produces("application/json")
> public List<Person> getPersons() {
> log.info("getPersons entered");
> final List<Person> persons = personService.getAll();
> return persons;
> }
>
> But on the inbound side I have questions.
>
> I have a simple method which I would like to send a JSON object to
> from an html page. I haven't found an example of this being done in
> the Jersey samples or through my Googling.
>
> I'm not sure how I would pass this json object to this URI. Should
> the JSON object be part of the path, sent as a parameter or either
> fine or still is there another way (or maybe just don't do that!)?
>
> @PUT
> @Produces("text/plain")
> @Consumes("application/json")
> public String updatePerson(@QueryParam("person") final Person
> person) {
> log.info("updatePerson entered: "+person.toString());
> personService.update(person);
> return "ok";
> }
>

> The JSON String I'm trying to send is: {"id":"1","name":"Frank
> Zappa","age":"62"}
>

Send the JSON as a request entity of the PUT request. This will
require that you utilize some JavaScript and XMLHttpRequest object
(ignore the fact that it begins with XML!).


@Path("{userid}")
@PUT
@Produces("text/plain")
@Consumes("application/json")
  public String updatePerson(final @PathParam("userid") String id,
final Person person) {
         log.info("updatePerson entered: "+person.toString());
         personService.update(person);
         return "ok"; // you can just return void if you wish as the
HTTP status code of 204
                              // means everything is OK.
   }


It is also important that a user and the list of users have distinct
URIs.

Paul.