miércoles, 22 de febrero de 2017

WS-REST 03. Definir 2 clases: Aplicación y Respuesta

1. Creamos la clase te tipo Application que va a sustituir a WEB.xml ya que estamos en un servlet tipo 3.1. Esta clase la llamaremos ApplicationConfig o como queramos. Yo la creo dentro de src/main/java/org/ximodante/jersey


package main.java.org.ximodante.jersey;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("rest") // set the path to REST web services
public class ApplicationConfig extends Application {}


Esta clase nos envia nuestros servicios web a la ruta http://localhost/NOMBRE_PROYECTO/rest En mi caso NOMBRE_PROYECTO=Jersey04 , y "rest" viene del ApplicationPath

  2. Dentro del mismo paquete cramos otra clase que llamamos en mi caso RESTfulHelloWord.

package main.java.org.ximodante.jersey;

import java.util.Date; 
import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.PathParam; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.Response; 

@Path("/") 
public class RESTfulHelloWorld{
  @GET 
  @Produces("text/html") 
  public Response getStartingPage() {    
    String output = "<h1>Hello World!<h1>" +      
      "<p>RESTful Service is running ... <br>Ping @ " + 
      new Date().toString() + 
      "</p<br>";    
    return Response.status(200).entity(output).build();   
  } 
} 

Tenemos que destacar @Path que se añade a nuestra ruta de ejecución:  http://localhost/Jersey04/rest

  3. Apretamos el botón de la derecha Maven - Update Project (y actualiza todas las dependencias y clases)

  4. Ejecutamos el proyecto en el servidor con Botón derecho Run As - Run on Server y seleccionamos nuestro servidor.

  5. Comprobamos que si se abre un navegador apunte a http://localhost/Jersey04/rest

  6. Saldrá :

Hello World!

RESTful Service is running ... Ping @ Wed Feb 22 10:19:13 CET 2017

No hay comentarios :

Publicar un comentario