Rest Post Method
In previous tutorial, I have learned how to work GET request with restful web-service. After
making a GET request to a REST service the natural progression is to POST information back to the server. In this
tutorial we will look at how to post JSON to rest controller and have it automatically convert JSON to object or
multiple objects. I am using @POST 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>
</dependency>
<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);
}
|
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;
}
}
|
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_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);
}
}
|
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 one method for Post
request. 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.
STEP TO TEST POST REQUEST
STEP : 1
I test this example using Postmap google App. First I checked from GET request, how many record exists using http://localhost:8089/RestWebService/webapi/personDetails/ URL.
STEP : 2
Now Select Post method from drop down, click on Headers tab, select Content-Type as Header application/json as value
STEP : 3
click on Body tab, select raw tab and insert JSON request object in body part
STEP : 4
In request object, I am inserting one person object. In this object, I set 3 values for address, created and name. I am not inserting ID value, because it will generated
from coding. Click on send button
When you click on send button, it insert into database and return person object in response
You can verfiy from GET method. After using POST method there are 4 record in hashmap as per display screen when you check record using GET method.