sábado, 31 de agosto de 2013

Spring REST

 - Rest (Representational State Transfer)  

         Rest is resource-oriented. Emphasizes the things and nouns that describe an application.
         - Introduction
             Representational: Rest resources can be represented on virtually any form(XML, JSON, HTML, etc)
             State: We are more concerned with the state of a resource than with the actions we can take against resource
             Transfer: REST involves transferring resource data, in soem representational form between applications.
             In other words:
                 REST is about transferring the state of resources in any form from a server to a client.
             For this reason, we should say: RESTful resources.
         REST vs SOAP Web Services
             Rest:  
                 Lightweight – sem muito extra xml markupt    , Resultados lidos por humanos, Fácil para construir. Sem necessidade de toolkits.
                 A enfase é na comunicação ponto a ponto por HTTP
                 Mais baseada no design web-based. Possui falta de padrões de suporte a segurança, política, confiabilidade no envio de mensagem.
             Soap
                 Fácil consumo, rígido na checagem de tipo, lida com erros, possui ferramentas de desenvolvimento.
                 É um protocolo para computação distribuida XML-based.    
         Rest with Spring
             - Controllers can handle all HTTP methods: GET, PUT, DELETE, POSR
             - @PathVariable annotation enables controllers to handle requests for parametrized URLs
             - <form:form> with HiddenHttpMethodFilter, make it possible to submit PUT and DELETE from HTML forms
             - Resources can be representes in XML, JSON, Atom, RSS, etc
             - @ResponseBody annotation and other HttpMethodConverter implementation for rendering amd marshall
             - RestTemplate simplifies client-side consumption of REST resources.
         Writing Controllers
             - Restless
                 @Controller
                 @RequestMapping("/displaySpittle.htm")
                 public class DisplaySpittleController{
                     @RequestMapping(method=RequestMethod.GET)
                         public String showSpittle(@RequestParam("id")longid,Modelmodel){
                             model.addAttribute(spitterService.getSpittleById(id));
                             return"spittles/view";
                     }
                 }
                 Ex of call:
                     http://localhost:8080/Spitter/display/displaySpittle.htm?id=123
             - RESTFUL
                 - Principle: No two resource could share the same URL. The path is parameterized.
                 - No query parameters and tend to be hierarchical.
                 Ex of call:
                     http://localhost:8080/Spitter/splitters/123
                     @Controller
                     @RequestMapping("/spittles")
                     public class SpittleController{
                         private SpitterService spitterService;
                         @Inject
                         public SpittleController(SpitterService spitterService){
                             this.spitterService=spitterService;
                         }
                         @RequestMapping(value="/{id}", method=RequestMethod.GET)
                         public StringgetSpittle(@PathVariable("id")longid,    Model model){
                             model.addAttribute(spitterService.getSpittleById(id));
                             return"spittles/view";
                         }
                     }
             - Verbs
                 POST: Post data to the server to be handled by a processor. Usually create a new resource
                     @RequestMapping(method=RequestMethod.POST)
                     @ResponseStatus(HttpStatus.CREATED) //201= created
                     public @ResponseBody Spittle createSpittle(@Valid Spittle spittle,
                                     BindingResult result,HttpServletResponse response) throws BindException{
                         if(result.hasErrors()){
                             thrownewBindException(result);
                         }
                         spitterService.saveSpittle(spittle);
                         response.setHeader("Location","/spittles/"+spittle.getId()); <--- Set resource location  
                         return spittle;
                     }
                     - POST operates against a URL that doesn't exist yet, because the resource is new.
                 GET: Retrieve information(list, or just name of element)
                 PUT: Update and save a data
                     @RequestMapping(value="/{id}",method=RequestMethod.PUT)
                     @ResponseStatus(HttpStatus.NO_CONTENT)    //Status should be se to 204<---- To let the client know if the process was successful
                     public void putSpittle(@PathVariable("id")longid, @Valid Spittlespittle){
                         spitterService.saveSpittle(spittle);
                     }
                 DELETE: Delete a data
                     @RequestMapping(value="/{id}",method=RequestMethod.DELETE)
                     @ResponseStatus(HttpStatus.NO_CONTENT)                    <---- To let the client know if the process was successful
                     public voiddeleteSpittle(@PathVariable("id")longid){
                         spitterService.deleteSpittle(id);
                     }
                 OPTIONS: Request avaiable options for communication with the server.
                 HEAD: Like Get, but a head should be returned
                 TRACE: Echoes the request body back to the client.
         - HTTP message converter
             @ResponseBody: Tells spring to return a object as a resource to client.
             - If use Jackson the object returned from the handler method will be given to the MappingJacksonHttpMessageConverter for conversion into JSON
             to the client.
         - Writing REST clients / RestTemplates
             Methods to interact with REST resouruces  
             Ex GET:
                 public Spittle[]retrieveSpittlesForSpitter(String username){
                     return new RestTemplate().getForObject(
                         "http://localhost:8080/Spitter/spitters/{spitter}/spittles", Spittle[].class,username); // {spitter} <--- username
                 }
                 or
                 public Spittle[]retrieveSpittlesForSpitter(Stringusername){
                     Map<String,String>urlVariables=newHashMap<String,String();
                     urlVariables.put("spitter",username);
                     return new RestTemplate().getForObject(
                         "http://localhost:8080/Spitter/spitters/{spitter}/spittles",Spittle[].class, urlVariables);
                 }
             PUT
                 public voidupdateSpittle(Spittlespittle) throws URISyntaxExceptione{
                     Stringurl="http://localhost:8080/Spitter/spittles/"+spittle.getId();
                     new RestTemplate().put(newURI(url),spittle);
                 }
                 OR
                 public voidupdateSpittle(Spittlespittle)throwsSpitterException{
                     restTemplate.put("http://localhost:8080/Spitter/spittles/{id}", spittle, spittle.getId());
                 }
             DELETE
                 public void deleteSpittle(longid){
                     restTemplate.delete("http://localhost:8080/Spitter/spittles/{id}",id));
                 }
             POST  
                 public Spitter postSpitterForObject(Spitterspitter){
                     RestTemplate rest = new RestTemplate();
                     return rest.postForObject("http://localhost:8080/Spitter/spitters",    spitter, Spitter.class);
                     }
                 }
                 Or
                 RestTemplate rest=new RestTemplate();
                 ResponseEntity<Spitter>response = rest.postForEntity("http://localhost:8080/Spitter/spitters",spitter,Spitter.class);
                 Spitter spitter=response.getBody();  <---- Body of Response returns Spitter
                 URI url=response.getHeaders().getLocation();
         - Writing <sf:form>
             To be used in PUT and DELETE
             <sf:form method="delete"modelAttribute="spitter">
                 ...
             </sf:form>
             result:
                 <form method="post">  
                     <input type="hidden"name="_method"value="delete"/>
                         ...
                 </form>

Nenhum comentário:

Postar um comentário