You are on page 1of 14

http://www.9lessons.info/2012/09/restful-webservices-api-using-java-and.

html
RESTful Web Services API using Java and MySQL
Are you working with multiple devices like iPhone, Android and Web, then take a
look at this post that explains you how to develop a RESTful API in Java.
Representational state transfer (REST) is a software system for distributing the data
to different kind of applications. The web service system produce status code
response in JSON or XML format.

Download War File

Download Project Source

Database
Sample database website table contains four columns id, title, description and url.
CREATE TABLE `website` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text,
`description` text,
`url` text,
PRIMARY KEY (`id`)
);

This tutorial required RESTful service support JAR files jersey-client-1.0.3.jar, jerseycore-1.0.3.jar, jersey-server-1.0.3.jar(Download), jsr311-api-1.0.jar(Download) and
asm-3.1.jar(Download). Copy these files into WEB-INF -> lib

FeedObjects.java
Create a new package called dto (Data Transaction Objects). Created transaction objects title,
description and url.
package dto;
public class FeedObjects {
private String title;
private String description;
private String url;

//Generate Getters and Setters


}

Project.java
Create a dao(Data Access Object) method GetFeeds with Arraylist datatype, using select
statement getting results from website table. Binding results into feedData object.
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import dto.FeedObjects;
public class Project
{
public ArrayList<feedobjects> GetFeeds(Connection connection) throws Exception
{
ArrayList<feedobjects> feedData = new ArrayList<feedobjects>();
try
{
PreparedStatement ps = connection.prepareStatement("SELECT title,description,url FROM
website ORDER BY id DESC");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
FeedObjects feedObject = new FeedObjects();
feedObject.setTitle(rs.getString("title"));
feedObject.setDescription(rs.getString("description"));
feedObject.setUrl(rs.getString("url"));
feedData.add(feedObject);
}
return feedData;
}
catch(Exception e)
{
throw e;
}
}
}

ProjectManager.java
Model class write the business logic and data validation.
package model;
import java.sql.Connection;
import java.util.ArrayList;
import dao.Database;
import dao.Project;
import dto.FeedObjects;
public class ProjectManager {
public ArrayList<feedobjects> GetFeeds()throws Exception {
ArrayList<feedobjects> feeds = null;
try {
Database database= new Database();
Connection connection = database.Get_Connection();
Project project= new Project();
feeds=project.GetFeeds(connection);
}
catch (Exception e) {
throw e;
}
return feeds;
}
}
FeedService.java
Web Services class for RESTful API.
package webService;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.ProjectManager;
import com.google.gson.Gson;
import dto.FeedObjects;
@Path("/WebService")
public class FeedService {
@GET

@Path("/GetFeeds")
@Produces("application/json")
public String feed()
{
String feeds = null;
try
{
ArrayList<feedobjects> feedData = null;
ProjectManager projectManager= new ProjectManager();
feedData = projectManager.GetFeeds();
Gson gson = new Gson();
System.out.println(gson.toJson(feedData));
feeds = gson.toJson(feedData);
}
catch (Exception e)
{
System.out.println("Exception Error"); //Console
}
return feeds;
}
}
If you want to convert GET to POST just do little change.

import javax.ws.rs.GET;
to
import javax.ws.rs.POST;
@GET
@Path("/GetFeeds")
to
@POST
@Path("/GetFeeds")
web.xml
The URL configuration file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>FirstProject</display-name>
<welcome-file-list>

<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>
com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>
<url-pattern>/REST/*</url-pattern>
</servlet-mapping>
</web-app>

Final URL
http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds
Here RESTfulProject is the project name, REST is the web.xml servelt mapping name,
WebService is REST API path and GetFeeds is the method name.
Note: For checking POST URLs user Poster extension for Chrome and Firefox.
JSON Output
[{
"title":"Ajax Image Upload without Refreshing Page using Jquery.",
"description":"Description Text",
"url":"http://www.9lessons.info/2011/08/ajax-image-upload-without-refreshing.html"
},
{
"title":"Java MySQL JSON Display Records using Jquery.",
"description":"Description Text",
"url":"http://www.9lessons.info/2012/08/java-json-jquery-display-records.html"
},
{
"title":"Java MySQL Insert Record using Jquery.",
"description":"Description Text",
"url":"http://www.9lessons.info/2012/07/java-mysql-insert-record-using-jquery.html"
}]
Next post I will explain RESTful web services with inputs and JSON data transformation.

RESTful Web Services JSON API Transformer with


Java
This post is the continuation of my previous last post, I had explained how to create
a basic RESTful web services API using Java, now I want to explain JSON transformer
to work with input Get and Post methods parameters. Just added a new class called
transformer it converts object data into JSON text output format.

Download War File

Download Project Source

Database
Sample database messages table contains three columns msg_id, message and user_id_fk.
CREATE TABLE `messages` (
`msg_id` int(11) NOT NULL AUTO_INCREMENT,
`message` TEXT,
`user_id_fk` INT,
PRIMARY KEY (`msg_id`)
);
This tutorial required RESTful service support JAR files jersey-client-1.0.3.jar, jersey-core1.0.3.jar, jersey-server-1.0.3.jar(Download), jsr311-api-1.0.jar(Download) and asm3.1.jar(Download). Copy these files into WEB-INF -> lib

FeedObjects.java
Create a new package called dto (Data Transaction Objects). Created transaction objects title,
description and url.
package dto;
public class FeedObjects {

private String msg_id;


private String message;
private String user_id;
//Generate Getters and Setters
}

Project.java
Create a dao(Data Access Object) method GetFeeds with Arraylist datatype, using select
statement getting results from messageses table where user_id_fk. Binding results into feedData
object.
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import dto.FeedObjects;
public class Project
{
public ArrayList<feedobjects> GetFeeds(Connection connection,,String User_ID) throws
Exception
{
ArrayList<feedobjects> feedData = new ArrayList<feedobjects>();
try
{
PreparedStatement ps = connection.prepareStatement("SELECT msg_id,message,user_id_fk
FROM messages WHERE user_id_fk=? ORDER BY msg_id DESC");
ps.setString(1,User_ID);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
FeedObjects feedObject = new FeedObjects();
feedObject.setTitle(rs.getString("msg_id"));
feedObject.setDescription(rs.getString("message"));
feedObject.setUrl(rs.getString("user_id_fk"));
feedData.add(feedObject);
}
return feedData;
}
catch(Exception e)

{
throw e;
}
}
}
ProjectManager.java
Model class write the business logic and data validation.
package model;
import java.sql.Connection;
import java.util.ArrayList;
import dao.Database;
import dao.Project;
import dto.FeedObjects;
public class ProjectManager {
public ArrayList<feedobjects> GetFeeds(String User_Id)throws Exception {
ArrayList<feedobjects> feeds = null;
try {
Database database= new Database();
Connection connection = database.Get_Connection();
Project project= new Project();
feeds=project.GetFeeds(connection,User_Id);
}
catch (Exception e) {
throw e;
}
return feeds;
}
}

FeedTransformer.java
Transformer class converts Java object result into JSON text format.
package transformer;
import java.util.ArrayList;
import com.google.gson.Gson;

import dto.FeedObjects;
public class FeedTransformer
{
public static String UserFeed(ArrayList<FeedObjects> feedData)
{
String feeds = null;
Gson gson = new Gson();
feeds = gson.toJson(feedData);
return feeds;
}
}
FeedService.java
Web Services class for RESTful API.
package webService;
import java.util.ArrayList;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import model.ProjectManager;
import com.google.gson.Gson;
import dto.FeedObjects;
@Path("/WebService")
public class FeedService {
@GET
@Path("/GetFeeds")
@Produces("application/json")
public String messageFeed(@QueryParam("userId") String User_Id)
{
String feeds = null;
try
{
ArrayList<FeedObjects> feedData = null;
ProjectManager projectManager= new ProjectManager();
feedData = projectManager.GetFeeds(User_Id);
feeds=FeedTransformer.UserFeed(feedData);
}
catch (Exception e)
{
System.out.println("Exception Error"); //Console
}

return feeds;
}
}
If you want to convert GET to POST just do little change.
import javax.ws.rs.GET;
import javax.ws.rs.QueryParam;
to
import javax.ws.rs.POST;
import javax.ws.rs.FormParam;
@GET
@Path("/GetFeeds")
to
@POST
@Path("/GetFeeds")
public String messageFeed(@QueryParam("userId") String User_Id)
to
public String messageFeed(@FormParam("userId") String User_Id)

You can test post method with Mozilla Firefox Add on Poster.

web.xml
The URL configuration file.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>FirstProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ServletAdaptor</servlet-name>
<servlet-class>
com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ServletAdaptor</servlet-name>

<url-pattern>/REST/*</url-pattern>
</servlet-mapping>
</web-app>
Final GET URL
http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds
Here RESTfulProject is the project name, REST is the web.xml servelt mapping name,
WebService is REST API path and GetFeeds is the method name.
Note: For checking POST URLs user Poster extension for Chrome and Firefox.
JSON Output
[{
"msg_id":"3",
"message":"Everything is possible. ",
"user_id":"2"
},
{
"msg_id":"1",
"message":"Make People fall in love with Your Ideas",
"user_id":"2"
}]

You might also like