martes, 10 de octubre de 2017

Crear un webservice RESTFUL en Spring (JSON)

Vamos a crear un webservice Restful con JSON en Spring. 


1 Crear un modulo maven para web.

2. Agregar lo siguiente en web.xml.  En el archivo web.xml se define el servlet DispatcherServlet.

<web-app id="WebApp_ID" version="2.4"

<display-name>Spring MVC Application</display-name>

<servlet>
<servlet-name>SpringRest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>SpringRest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

3. Crear el archivo SpringRest-servlet.xml para la configuracion de spring mvc. En el archivo SpringRest-servlet.xml se definen  varias cosas entre ellas se carga el bean del servicio web, y se definen los beans para convertir de pojo a json y de json a pojo.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing 
infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />



<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/" />
<beans:property name="suffix" value=".jsp" />

</beans:bean>
        <resources mapping="/**" location="/" />

<context:component-scan base-package="com.webservices" />

</beans:beans>

4. Crear el modelo employee



package com.model;



import java.io.Serializable;

import java.util.Date;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;

public class Employee implements Serializable {

private static final long serialVersionUID = -7788619177798333712L;

private int id;
private String name;
private Date createdDate;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
@JsonSerialize(using = DateSerializer.class)
public Date getCreatedDate() {
return createdDate;
}

public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}

}


5. Crear una clase estatica para las URIs
package com.model;



public class EmpRestURIConstants {


public static final String DUMMY_EMP = "/rest/emp/dummy";
public static final String GET_EMP = "/rest/emp/{id}";
public static final String GET_ALL_EMP = "/rest/emps";
public static final String CREATE_EMP = "/rest/emp/create";
public static final String DELETE_EMP = "/rest/emp/delete/{id}";
}


6. Crear el controlador principal.

package com.webservices;


import java.util.ArrayList;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.model.Employee;
import com.model.EmpRestURIConstants;

/**
 * Handles requests for the Employee service.
 */
@Controller
public class EmployeeController {
private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);
//Map to store employees, ideally we should use database
Map<Integer, Employee> empData = new HashMap<Integer, Employee>();
@RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)
public @ResponseBody Employee getDummyEmployee() {
logger.info("Start getDummyEmployee");
Employee emp = new Employee();
emp.setId(9999);
emp.setName("Dummy");
emp.setCreatedDate(new Date());
empData.put(9999, emp);
return emp;
}
@RequestMapping(value = EmpRestURIConstants.GET_EMP, method = RequestMethod.GET)
public @ResponseBody Employee getEmployee(@PathVariable("id") int empId) {
logger.info("Start getEmployee. ID="+empId);
return empData.get(empId);
}
@RequestMapping(value = EmpRestURIConstants.GET_ALL_EMP, method = RequestMethod.GET)
public @ResponseBody List<Employee> getAllEmployees() {
logger.info("Start getAllEmployees.");
List<Employee> emps = new ArrayList<Employee>();
Set<Integer> empIdKeys = empData.keySet();
for(Integer i : empIdKeys){
emps.add(empData.get(i));
}
return emps;
}
@RequestMapping(value = EmpRestURIConstants.CREATE_EMP, method = RequestMethod.POST)
public @ResponseBody Employee createEmployee(@RequestBody Employee emp) {
logger.info("Start createEmployee.");
emp.setCreatedDate(new Date());
empData.put(emp.getId(), emp);
return emp;
}
@RequestMapping(value = EmpRestURIConstants.DELETE_EMP, method = RequestMethod.PUT)
public @ResponseBody Employee deleteEmployee(@PathVariable("id") int empId) {
logger.info("Start deleteEmployee.");
Employee emp = empData.get(empId);
empData.remove(empId);
return emp;
}
}

@ResponseBody traduce el bean a un formato especificado en la configuracion. En este caso se convierte automaticamente a una version de Json del bean. @RequestMapping es usado para mapear la url al metodo. @PathVariable es usado para mapear el path de variable.



7. Usaremos postman para probar los servicios web:

Empezamos probando el health del servicio web. 
http://localhost:8080/SpringRest/rest/emp/dummy













Para extraer un empleado en particular:
http://localhost:8080/SpringRest/rest/emp/9999/














Para crear un registro para un empleado nuevo, se utiliza el siguiente webservice con el metodo POST con el siguiente body: {"id": 1,"name": "Luis Mi"}
http://localhost:8080/SpringRest/rest/emp/create














Para extraer el empleado que acabamos de generar:

http://localhost:8080/SpringRest/rest/emp/1/




No hay comentarios:

Publicar un comentario