Springrest:: Jersey

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

SpringRest:

Spring will load Jackson2JsonMessageConverter into its application context


automatically. Whenever you request resource as json with
accept headers=”Accept=application/json”, then Jackson2JsonMessageConverter
comes into picture and convert resource to json format.

@RestController

public class CountryController {

@RequestMapping(value = "/countries", method = RequestMethod.GET,


headers="Accept=application/json")

public List getCountries()

return listofCountries;

}}

XML format
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class HelloWorld {
    @XmlElement
    private String message;
}
@XmlRootElement – specifies the root tag of each HelloWorld record in xml.

@XmlElement – specifies the child element for each attribute of HelloWorld record.

@XmlAccessorType(XmlAccessType.FIELD) – specifies that fields are considered to


be serialized

How Spring controller acts as a Rest service ?

We have @ResponseBody before the return type of a method in method signature which


indicates to Spring that ,the returned value from this method will not be a view rather it has to
be read from the response body.

RestTemplate: http://javainsimpleway.com/spring-resttemplate-crud-operations-with-json/

Jersey:
Jersey internally uses Jackson for Json Handling, so it will be used to marshal pojo
objects to JSON
@Path("/countries")
public class CountryRestService {
  
  
@GET
    @Path("{id: d+}")
    @Produces(MediaType.APPLICATION_JSON)
public Country getCountryById(@PathParam("id") int id)
{
  List listOfCountries = new ArrayList();
  listOfCountries=createCountryList();
 
  for (Country country: listOfCountries) {
   if(country.getId()==id)
    return country;
  }
  
  return null;
}

@Path
@PathParam
@QueryParam
@MatrixParam
@HeaderParam
@CookieParam

You might also like