Via Cà Matta 2 - Peschiera Borromeo (MI)
+39 02 00704272
info@synaptica.info

Simplest working example of REST json and xml

Simplest working example of REST json and xml

Hello folks,

Today i will show you a complete working REST example with Glassfish V3.

I am very happy of the new java EE 6 specification that brings me to use EJB technology. Before now i never used EJB cause there was too much complexity in configuration.

Now you have to use only few annotation and let the container works for you!

We want to return complex object from the REST interface, like for example a Person:

We used few annotation to annotate the field that will be an xml element (or a json element). That’s the only information the container needs for marshalling/unmarshalling complex object into Xml or Json.

Now we need the REST class,  as simple as follow:

We still need a boring configuration step in the web.xml, add the following:

<servlet>

<servlet-name>Jersey Web Application</servlet-name>

<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>Jersey Web Application</servlet-name>

<url-pattern>/*</url-pattern>

</servlet-mapping>

We already finished our “complex” REST interface, point your browser to http://localhost:8080/projectname/person
and you get something like this:

person

Changing the @Produces(“application/xml”) annotation to  @Produces({“application/xml”,”application/json”}) makes the json data retrieval available, depending on the client that made the request, the container will give the appropriate response. For example making the request from javascript will return a json like this:

{“id”:”0″,”name”:”Riccardo”,”surname”:”Casatta”}

Enjoy the new Simpler way of making things in java EE 6!

Tags: , , , , , ,

Lascia un commento