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 OTher Methods

In previous tutorial, I discussed GET and POST method. Now we discuss other method in restful webservice. The primary and most commonly used HTTP methods are GET, POST, PUT and DELETE. These correspond to read, create, update, and delete (or CRUD) operations, respectively. There are a number of other methods, OPTIONS and HEAD are used more often than others. 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);

public Person addPerson(Person person);
public Person updatePerson(Person person);
public Person deletePerson(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);
}
@Override
public Person addPerson(Person person){
person.setId(persons.size() + 1);
persons.put(person.getId(), person);
return person;
}
@Override
public Person updatePerson(Person person){
if(person.getId() <= 0 )
return null;
persons.put(person.getId(), person);
return person;
}
@Override
public Person deletePerson(long id){
return persons.remove(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. In this class I am using CRUD (Create, Read, Update, Delete) operation.



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_JSON)
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;
}


@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Person addPerson(Person person){
return dao.addPerson(person);
}


@PUT
@Path("/{personId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Person updatePerson(@PathParam("personId") long personId,
Person person){
person.setId(personId);
return dao.updatePerson(person);
}


@DELETE
@Path("/{personId}")
@Produces(MediaType.APPLICATION_JSON)
public Person deletePerson(@PathParam("personId") long personId){
return dao.deletePerson(personId);
}


}

In this class I have created one webservice PersonService in which it handle request for personDetails. In this service, I am creating methods for GET, POST, PUT, DELETE requests. In Post request, I am adding record in hashmap (you can use database. It is my temporary database) and return Person objectresponse after that I will get record from GET request. In previous tutorial (click here), I have explained, how will you test GET and POST methods. For PUT and DELETE method you can use below steps:



Step 1: First you will check record by using GET request
http://localhost:8089/RestWebService/webapi/personDetails/
Here you will see 3 person detail in JSON response in Postman App. Now I want to update one person detail which ID is 1. I will update name and address. Currently username is user1 and address is Delhi
Step 2: select PUT method option from dropdown - > click on Body tab -> click on row option as per highlighted option in below screen. Insert updated Person record in JSON format -> click on send button





Step3 : After click on send button, Person object will be updated in record. you will verify from GET request URL. Select GET metod option from drop down and type this URL http://localhost:8089/RestWebService/webapi/personDetails

Now I want delete record from database. First select DELETE method option in drop down and type http://localhost:8089/RestWebService4/webapi/personDetails/2 URL with person ID which you want to delete and then click on send button. Record will be deleted from dababase. For verify, you can use GET method request.


     << Previous
Next >>