Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous
Next >>     


Rest Get Method

In previous example, We have discussed how to create simple rest web-service. Now I will create one rest web-service for GET method which return XML or JSON response. In this example I have created two method for getting data from database (database is temporary class) or based on ID. I am using @GET annotation in this example. The code of this tutorial is going to be based on Jersey. If you are not able to create jersey project, click here. Let's show the structure of the project:





pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.rest.technology</groupId>
<artifactId>RestWebService</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>RestWebService</name>

<build>
<finalName>RestWebService</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<inherited>true</inherited>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.glassfish.jersey</groupId>
<artifactId>jersey-bom</artifactId>
<version></version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<!-- use the following artifactId if you don't need servlet 2.x compatibility -->
<!-- artifactId>jersey-container-servlet</artifactId -->
</dependency>
<!-- this to get JSON support -->
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>
</dependencies>
<properties>
<jersey.version>2.21</jersey.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>


In this pom.xml, I have used jersey-media-moxy dependency for getting JSON response and jersey-container-servlet-core dependency is used to configure Jersey dependency with this project.



you create a file called web.xml in the WebContent\WEB-INF folder as the following:

web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>

<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>Jersey Web Application </servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>
jersey.config.server.provider.packages </param-name>
<param-value>com.rest.technology </param-value>
</init-param>
<load-on-startup>1 </load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Jersey Web Application </servlet-name>
<url-pattern>/webapi/* </url-pattern>
</servlet-mapping>

</web-app>

In web.xml, I am using org.glassfish.jersey.servlet.ServletContainer servlet for configure restful webservice. I have configure com.rest.technology package for searching all annotations and create a one instance when application start using load-on-startup. In this example /webapi/* pattern use for restful URL.



DatabaseClass.java
package com.rest.technology.database;

import java.util.HashMap;
import java.util.Map;

import com.rest.technology.model.Client;

public class DatabaseClass {

private static Map<Long, Person> persons = new HashMap<Long, Person>();

public static Map<Long, Person> getPersons() {
return persons;
}
}

I am not using any database. So I am creating a temporary class com/rest/technology/database/DatabaseClass.java that will work like a database.



Person.java
package com.rest.technology.model;

import java.util.Date;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "Person")
public class Person {

private long id;
private String name;
private String address;
private Date created;

public Person() {
}

public Person(long id, String name, String address) {
super();
this.id = id;
this.name = name;
this.address = address;
this.created = new Date();
}

public long getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public Date getCreated() {
return created;
}

public void setCreated(Date created) {
this.created = created;
}
}

Here we have a simple POJO (Plain Old Java Object) that contains information about Person. It contains id, name, address and createdDate variable. I have created @XmlRootElement annotation on class level. This annotation use for when restful service return XML response.



PersonDao.java
package com.rest.technology.RestWebService.dao;

import java.util.List;

import com.rest.technology.model.Person;

public class PersonDao {

public List<Person> getAllPersons();

public <Person> getPerson(long id);
}

I have created PersonDao interface. And I am creating two methods in this interface. getAllPersons() method will used to get all person detail lists and getPerson() method use for person detail based on person ID.



PersonDaoImpl.java
package com.rest.technology.RestWebService.dao.impl;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;

import com.rest.technology.RestWebService.dao.PersonDao;
import com.rest.technology.RestWebService.model.Person;
import com.rest.technology.db.DataBase;

public class PersonDaoImpl implements PersonDao {

private Map<Long, Person> persons = DataBase.getPersons();
public PersonDaoImpl(){
persons.put(1L, new Person(1L, "user1", "Delhi"));
persons.put(2L, new Person(2L, "user2", "Noida"));
persons.put(3L, new Person(3L, "user3", "Gurgaon"));
}

@Override
public List<Person> getAllPersons(){
return new ArrayList<Person>(persons.values()); }
@Override
public <Person> getPerson(long id){
return persons.get(id); }
}

PersonDaoImpl is the implementation of PersonDao Interface. I am using DataBase.java class for getting all person details. I have created DataBase.java for temporary database.



PersonService.java
package com.rest.technology.RestWebService.service;

import java.util.List;
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.MediaType;

import com.rest.technology.RestWebService.model.Person;
import com.rest.technology.RestWebService.dao.PersonDao;
import com.rest.technology.RestWebService.dao.impl.PersonDaoImpl;

@Path("/personDetails")
public class PersonService {

PersonDao dao = new PersonDaoImpl();

@GET
@Produces(MediaType.APPLICATION_XML)
public List<Person> getPersonsList(){
return dao.getAllPersons();
}

@GET
@Path("/{personId}")
@Produces(MediaType.APPLICATION_XML)
public Person getPerson(@PathParam("personId") long personId){
Person person = dao.getPerson(personId);
return person;
}

}

In this class I have created one webservice PersonService in which it handle request for personDetails. I am creating two methods for GET request and it will return XML response. getPersonList() method will return all Person list exists in database (temporary database) and getPersonsList method will return xml response based on personId. @PathParam annotation injects value from URI to your method input parameters.
I am using Chrome Postman application for testing this rest web-services. If you don't have Postman application, so you can download Postman application from chrom site (https://chrome.google.com/webstore/category/extensions?hl=en-us). In Search Extensions text box type Postman client and install in your desktop or laptop.

In below image you can see postman icon in you chrom app type chrome://apps/ in chrome.

When you click on postman icon you will get above screen. Here you can get option for testing based on GET, POST, PUT etc. methods. You can set param parameters and different-2 options in Postman App. Now I have to test GET method So I set GET(default set) in drop down and type http://localhost:8089/RestWebService3/webapi/personDetails url and click on Send button. I will call getPersonsList() method from PersonService.java. You can see result in below screen.

In above screen I am getting all person detail in list from http://localhost:8089/RestWebService3/webapi/personDetails URL. If I need only one person detail based on ID, just I add personID value in this URL. So when I test with http://localhost:8089/RestWebService3/webapi/personDetails/2 URL, it will call getPerson() method and you will get person detail which have ID is 2.

<person>
<address>Noida</address>
<created>2015-10-21T21:50:21.883+05:30</created>
<id>2</id>
<name>user2</name>
</person>

Now, if I need JSON response when I test above URL (http://localhost:8089/RestWebService3/webapi/personDetails/2), First you need only change in PersonService.java. You will change APPLICATION_XML to APPLICATION_JSON--

PersonService.java
.............
.............
.............

@GET
@Produces(MediaType.APPLICATION_XML)
public List<Person> getPersonsList(){
return dao.getAllPersons();
}

@GET
@Path("/{personId}")
@Produces(MediaType.APPLICATION_JSON)
public Person getPerson(@PathParam("personId") long personId){
Person person = dao.getPerson(personId);
return person;
}

}

Second step, you will set dependency jersey-media-moxy in pom.xml which I have already set in pom.xml

<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
</dependency>

Now if you run this program you will get below output.

{
"address": "Noida",
"created": "2015-10-21T22:23:35.627+05:30",
"id": 2,
"name": "user2"
}

     << Previous
Next >>