banner



How To Retrieve Data From Rest Uri In Java

Welcome to Restful Spider web Services Tutorial in Java. REST is the acronym for REpresentational Land Transfer. Remainder is an architectural style for developing applications that can exist accessed over the network. REST architectural fashion was brought in light past Roy Fielding in his doctoral thesis in 2000.

Restful Web Services

Restful Spider web Services is a stateless client-server architecture where spider web services are resources and can exist identified by their URIs.

Residue Client applications tin can utilize HTTP Become/POST methods to invoke Restful web services. Residual doesn't specify any specific protocol to use, but in virtually all cases it's used over HTTP/HTTPS. When compared to SOAP web services, these are lightweight and doesn't follow whatever standard. We tin can utilize XML, JSON, text or any other type of information for request and response.

Coffee RESTful Web Services API

Java API for RESTful Spider web Services (JAX-RS) is the Java API for creating Balance spider web services. JAX-RS uses annotations to simplify the development and deployment of web services. JAX-RS is part of JDK, and then you don't need to include annihilation to employ it's annotations.

Restful Spider web Services Annotations

Some of the of import JAX-RS annotations are:

  • @Path: used to specify the relative path of class and methods. Nosotros can get the URI of a webservice by scanning the Path annotation value.
  • @Get, @PUT, @POST, @DELETE and @Caput: used to specify the HTTP asking type for a method.
  • @Produces, @Consumes: used to specify the request and response types.
  • @PathParam: used to bind the method parameter to path value by parsing it.

Restful Spider web Services and Soap

  1. Soap is a protocol whereas Rest is an architectural style.
  2. Soap server and client applications are tightly coupled and bind with the WSDL contract whereas there is no contract in Rest web services and client.
  3. Learning bend is easy for Balance when compared to SOAP web services.
  4. Residue web services request and response types can be XML, JSON, text etc. whereas Soap works with XML only.
  5. JAX-RS is the Java API for Residuum web services whereas JAX-WS is the Coffee API for SOAP web services.

REST API Implementations

There are two major implementations of JAX-RS API.

  1. Jersey: Bailiwick of jersey is the reference implementation provided by Sun. For using Jersey equally our JAX-RS implementation, all we need to configure its servlet in web.xml and add required dependencies. Annotation that JAX-RS API is part of JDK non Jersey, and then nosotros accept to add together its dependency jars in our awarding.
  2. RESTEasy: RESTEasy is the JBoss project that provides JAX-RS implementation.

Java Restful Web Services Tutorial

Let'due south run across how easy to create Restful web service using Jersey and and then RESTEasy. We will exist exposing post-obit methods over HTTP and use Chrome Postman extension to test these.

URI HTTP Method Description
/person/{id}/getDummy Go Returns a dummy person object
/person/add POST Adds a person
/person/{id}/delete Go Delete the person with 'id' in the URI
/person/getAll GET Get all persons
/person/{id}/become GET Get the person with 'id' in the URI

Jersey Restful Web Services

Create a dynamic spider web projection then convert it to Maven to become the skeleton of your web services project. Beneath image shows the projection structure of the final project.

JAXRS Jersey Project

Let's look at the Jersey dependencies we have in pom.xml file.

          <project xmlns="https://maven.apache.org/POM/iv.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-four.0.0.xsd">   <modelVersion>4.0.0</modelVersion>   <groupId>JAXRS-Example</groupId>   <artifactId>JAXRS-Instance</artifactId>   <version>0.0.1-SNAPSHOT</version>   <packaging>state of war</packaging>      <dependencies>         <dependency>             <groupId>com.sun.jersey</groupId>             <artifactId>jersey-server</artifactId>             <version>1.19</version>         </dependency>         <dependency>             <groupId>com.sun.jersey</groupId>             <artifactId>jersey-servlet</artifactId>             <version>1.xix</version>         </dependency>         <dependency>             <groupId>com.sun.jersey</groupId>             <artifactId>jersey-customer</artifactId>             <version>1.nineteen</version>         </dependency>   </dependencies>      <build>     <sourceDirectory>src</sourceDirectory>     <plugins>       <plugin>         <artifactId>maven-war-plugin</artifactId>         <version>2.6</version>         <configuration>           <warSourceDirectory>WebContent</warSourceDirectory>           <failOnMissingWebXml>false</failOnMissingWebXml>         </configuration>       </plugin>       <plugin>         <artifactId>maven-compiler-plugin</artifactId>         <version>three.three</version>         <configuration>           <source>1.vii</source>           <target>1.vii</target>         </configuration>       </plugin>     </plugins>   </build> </project>                  

We are non required to add jersey-customer dependencies but if you are writing java program to invoke a Balance web service using Jersey so it's required.

At present let's await at the deployment descriptor to larn how to configure Jersey to create our web application.

          <?xml version="1.0" encoding="UTF-eight"?> <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-example" xmlns="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="three.1">   <display-proper name>JAXRS-Example</display-name>  <!-- Bailiwick of jersey Servlet configurations -->     <servlet>     <servlet-name>Jersey REST Service</servlet-name>     <servlet-class>com.sun.bailiwick of jersey.spi.container.servlet.ServletContainer</servlet-form>     <init-param>       <param-name>com.lord's day.jersey.config.belongings.packages</param-name>       <param-value>com.journaldev</param-value>     </init-param>     <load-on-startup>1</load-on-startup>   </servlet>   <servlet-mapping>     <servlet-name>Jersey REST Service</servlet-name>     <url-pattern>/*</url-pattern>   </servlet-mapping>   <!-- Jersey Servlet configurations -->  </web-app>                  

That'southward all is required to plugin Jersey into our web application, in our java code we will be using JAX-RS annotations. Notice the value of init parameter com.sun.jersey.config.property.packages to provide parcel that will be scanned for web service resource and methods.

REST Example Model Classes

First of all we volition create two model beans – Person for our application data and Response for sending response to client systems. Since we will be sending XML response, the beans should be annotated with @XmlRootElement, hence we have this class.

          bundle com.journaldev.jaxrs.model;  import javax.xml.bind.notation.XmlRootElement;  @XmlRootElement (name="person") public course Person { 	private String name; 	private int age; 	private int id;  	public String getName() { 		return name; 	}  	public void setName(String proper name) { 		this.name = name; 	}  	public int getAge() { 		render age; 	}  	public void setAge(int historic period) { 		this.age = age; 	}  	public int getId() { 		return id; 	}  	public void setId(int id) { 		this.id = id; 	} 	 	@Override 	public String toString(){ 		return id+"::"+proper name+"::"+historic period; 	}  }                  
          package com.journaldev.jaxrs.model;  import javax.xml.demark.notation.XmlRootElement;  @XmlRootElement public class Response {  	private boolean status; 	private String bulletin;  	public boolean isStatus() { 		return status; 	}  	public void setStatus(boolean condition) { 		this.status = status; 	}  	public String getMessage() { 		return bulletin; 	}  	public void setMessage(Cord message) { 		this.message = message; 	} }                  

REST Web Services Tutorial Services

Based on our URI construction, below is the service interface and it's implementation code.

          package com.journaldev.jaxrs.service;  import com.journaldev.jaxrs.model.Person; import com.journaldev.jaxrs.model.Response;  public interface PersonService {  	public Response addPerson(Person p); 	 	public Response deletePerson(int id); 	 	public Person getPerson(int id); 	 	public Person[] getAllPersons();  }                  
          packet com.journaldev.jaxrs.service;   import java.util.HashMap; import java.util.Map; import java.util.Set;  import javax.ws.rs.Consumes; import javax.ws.rs.Become; import javax.ws.rs.Mail; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.cadre.MediaType;  import com.journaldev.jaxrs.model.Person; import com.journaldev.jaxrs.model.Response;  @Path("/person") @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public class PersonServiceImpl implements PersonService {  	private static Map<Integer,Person> persons = new HashMap<Integer,Person>(); 	 	@Override 	@Mail service     @Path("/add") 	public Response addPerson(Person p) { 		Response response = new Response(); 		if(persons.go(p.getId()) != null){ 			response.setStatus(imitation); 			response.setMessage("Person Already Exists"); 			return response; 		} 		persons.put(p.getId(), p); 		response.setStatus(truthful); 		response.setMessage("Person created successfully"); 		render response; 	}  	@Override 	@Get     @Path("/{id}/delete") 	public Response deletePerson(@PathParam("id") int id) { 		Response response = new Response(); 		if(persons.get(id) == null){ 			response.setStatus(fake); 			response.setMessage("Person Doesn't Exists"); 			render response; 		} 		persons.remove(id); 		response.setStatus(true); 		response.setMessage("Person deleted successfully"); 		render response; 	}  	@Override 	@Go 	@Path("/{id}/go") 	public Person getPerson(@PathParam("id") int id) { 		render persons.get(id); 	} 	 	@Get 	@Path("/{id}/getDummy") 	public Person getDummyPerson(@PathParam("id") int id) { 		Person p = new Person(); 		p.setAge(99); 		p.setName("Dummy"); 		p.setId(id); 		return p; 	}  	@Override 	@Get 	@Path("/getAll") 	public Person[] getAllPersons() { 		Set<Integer> ids = persons.keySet(); 		Person[] p = new Person[ids.size()]; 		int i=0; 		for(Integer id : ids){ 			p[i] = persons.get(id); 			i++; 		} 		return p; 	}  }                  

Most of the code is self explanatory, spend some time to familiarize yourself with JAX-RS annotations @Path, @PathParam, @Postal service, @Get, @Consumes and @Produces.

Restful Web Services Examination

That's it. Our spider web service is ready, just export it as State of war file and put it inside Tomcat webapps directory or deploy into any other container of your option.

Below are some of the tests performed using Postman chrome extension for this spider web service. Note that we have to provide Accept and Content-Type values as "awarding/xml" in request header as shown in below prototype.

JAXRS Headers Accept

That's all for creating web services using Jersey JAX-RS implementation. As you can see that near of the lawmaking is using JAX-RS annotations and Jersey is plugged in through deployment descriptor and dependencies.

RESTEasy RESTful Web Services Example

We will use all the business logic developed in Bailiwick of jersey project, but rather than making changes to the same projection, I take created a new project. Create a dynamic web project and convert it to Maven project. Then copy all the java classes – Person, Response, PersonService and PersonServiceImpl. Below is the final project afterward nosotros are done with all the changes.

JAXRS RestEasy Project

Add below RESTEasy dependencies in pom.xml file.

          <dependency> 	<groupId>org.jboss.resteasy</groupId> 	<artifactId>resteasy-jaxrs</artifactId> 	<version>three.0.13.Last</version> </dependency> <dependency> 	<groupId>org.jboss.resteasy</groupId> 	<artifactId>resteasy-jaxb-provider</artifactId> 	<version>iii.0.13.Final</version> </dependency>                  

Beneath is the web.xml file where nosotros are configuring Resteasy servlet.

          <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">   <display-proper name>JAXRS-Example-RestEasy</brandish-name>           <listener>       <listener-class>          org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap       </listener-class>    	</listener>         <servlet>         <servlet-proper noun>resteasy-servlet</servlet-name>         <servlet-course>             org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher         </servlet-class>         <init-param>         <param-name>javax.ws.rs.Awarding</param-proper name>         <param-value>com.journaldev.jaxrs.resteasy.app.MyApp</param-value>     </init-param>     </servlet>        <servlet-mapping>         <servlet-name>resteasy-servlet</servlet-name>         <url-blueprint>/*</url-pattern>     </servlet-mapping> 	 </web-app>                  

Detect the init-param where are providing MyApp class as value, here we are extending javax.ws.rs.core.Application form as shown below.

          package com.journaldev.jaxrs.resteasy.app;  import java.util.HashSet; import coffee.util.Set;  import javax.ws.rs.core.Application;  import com.journaldev.jaxrs.service.PersonServiceImpl;  public class MyApp extends Application { 	 	private Fix<Object> singletons = new HashSet<Object>();  	public MyApp() { 		singletons.add(new PersonServiceImpl()); 	}  	@Override 	public Set<Object> getSingletons() { 		return singletons; 	}  }                  

RESTEasy Web Services Test

That'due south it. Our web service is ready with RESTEasy JAX-RS implementation. Below are some of the output from Postman chrome extension test.

That'southward all for Restful Web Services Tutorial, I promise you learned about JAX-RS annotations and understood the benefits of having standard API that helped u.s.a. in reusing code and moving from Jersey to RESTEasy so piece of cake.

How To Retrieve Data From Rest Uri In Java,

Source: https://www.journaldev.com/9170/restful-web-services-tutorial-java

Posted by: stinsonhavelf.blogspot.com

0 Response to "How To Retrieve Data From Rest Uri In Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel