sábado, 21 de febrero de 2015

Servicio REST

SERVICIO REST

Continuando con el proyecto anterior Vaadin,Spring,Hibernate vamos a crear un servicio REST sencillo donde listemos los usuarios de la BD, todo esto utilizando Spring. (Para saber que es REST remitirse al link)

Ya antes en el archivo web.xml habiamos mapeado la clase org.springframework.web.servlet.DispatcherServlet de Spring y estaba mapeada algo asì:

 <servlet-mapping>  
     <servlet-name>dispatcher</servlet-name>  
     <url-pattern>/html/*</url-pattern>  
   </servlet-mapping>  


Y tenemos el archivo asociado dispatcher-servlet.xml donde definimos diferentes View Resolver, entre ellos para json y xml.

Teniendo lo anterior podemos crear la siguiente clase:

 package com.ejemplo.vaadin.rest;  
 import com.ejemplo.vaadin.dao.DaoUsuario;  
 import com.ejemplo.vaadin.entidades.Usuario;  
 import java.util.ArrayList;  
 import java.util.List;  
 import javax.servlet.http.HttpServletRequest;  
 import javax.servlet.http.HttpServletResponse;  
 import org.springframework.beans.factory.annotation.Autowired;  
 import org.springframework.stereotype.Controller;  
 import org.springframework.web.bind.annotation.RequestMapping;  
 import org.springframework.web.bind.annotation.RequestMethod;  
 import org.springframework.web.servlet.ModelAndView;  
 /**  
  *  
  * @author josorio  
  */  
 @Controller  
 public class UsuariosController {  
   @Autowired  
   private DaoUsuario daoUsuario;  
   /**  
    * Lista todos los usuarios de la BD  
    * @param request  
    * @param response  
    * @return   
    */  
   @RequestMapping( method = {RequestMethod.GET}, value = "/listarusuarios" )  
   public ModelAndView obtener10Parqueaderos(HttpServletRequest request, HttpServletResponse response)  
   {  
     ModelAndView retorno = new ModelAndView();  
     List<Usuario> listaEntidades;  
     try{        
       listaEntidades = daoUsuario.listar();  
       if( listaEntidades == null )  
       {  
         listaEntidades = new ArrayList<Usuario>();  
       }  
     }catch(Exception e){  
       System.out.println("Error "+e.getMessage());  
       listaEntidades = new ArrayList<Usuario>();  
     }  
     retorno.addObject( "cantidad", listaEntidades.size() );  
     retorno.addObject( "datos", listaEntidades );  
     return retorno;  
   }  
 }  

Ya con esto y si visitamos las urls:
../MavenEjemplo/html/listarusuarios.xml ó /MavenEjemplo/html/listarusuarios.json veremos nuestro webservice tipo REST corriendo.