9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Sunday, September 16, 2012

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.

RESTful Web Services using Java and MySQL

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, jersey-core-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

RESTful Web Services using Java and MySQL

Download Project Source link contains all these JARs.

Previous Tutorials: Java MySQL Insert Record using Jquery. and Java MySQL JSON Display Records using Jquery.

Package structure for more details please check my previous java tutorials.
RESTful Web Services using Java and MySQL

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
}
Explained generating Getters and Setter methods in this following tutorialJava MySQL JSON Display Records using Jquery.

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/web-app_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.
Comments
{ 42 comments }
Pradyut said...

post how to integrate oauth with jersey

Anonymous said...

thanks

Anonymous said...

Hi man, Thanks for all your postings... Please post how to create a toolbar for all web browsers.

thanks

Kian It said...

Good!
خوبه !

Carlos said...

Wow! Very good article.
What minimum version of JEE is required and it works with any application server? Tomcat?

Rahul Kashyap said...

Thanks For sharing this post :)

Anonymous said...

could make an example spring3 + mybatis3 + primefaces3,


Thank!!!...

Sandeep K Nair said...

Please post on how to create the same with php. and how to communicate via soap messages.

Anonymous said...

Yes it works with Tomcat also

Anonymous said...

You may want to close you connection :). Perhaps too many concepts at once, and too much detail.

Not bad overall!

opensas opensas said...

I think DTO stands for data transfer object... Am I wrong???

pranava said...

Its quite a good article..:) which just refreshed my REST Work sometime back..Thanks

Anonymous said...

Very good work, thank you very much !

Could you please also make one based on PHP?

Anonymous said...

In response to my previous message for a version on PHP : you already did it !

http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html

Thanks a lot for all your work

harroop gill said...

nice work . I like it

Anonymous said...

What's up with the WCF web service in .Net. Have tried everything to get rid of the 400 Bad request error on the server side when uploading an image. It seems like everyone else out there is having the same problem. I have not seen a complete project yet on it.

Sreenivas said...

Hi Srininvas,
Please clarify my doubts.

1.In Rest full services who will convert object to json,object o html,object to text where as in jaxws jaxb binding will take care of this. In rest converting obj to xml jaxb only what abt others like html,json,text.

2.Directly the JSON data is transffered from the consumer to provider or any thing bindings happed in the middle.

3. If Directly Json data is transffered where is
security in jaxrs.
Please help on these questions.
Thanks a lot Srinivas !...

shorav said...

Hello PLease clarify me here -

Database database = new Database();
Connection connection = database.Get_Connection();
Project project = new Project();

"DataBase" class is not available and thus showing error to me?? Is it built in??

shorav said...

I think DataBase class is in the dao package that is not available in the example program. Please check it.

Gurpreet said...

Great work, I really apreceate it.

Omama Moin said...

Great Work!!!!

MOON KUNDU said...

awesome..really nice

Santosh Pardeshi said...

Hi Srinivas,

I am santosh. I had type the same code u have shown above. While running it give me an error as
Error :"INFO: Servlet ServletAdaptor is currently unavailable"

can u plz tell me how to help me by showing me servlet code snap. Plz Plz i need to learn a how ESTFul webservice is created. Because I have to use webservice for my Android App.

Anush Reddy said...

Hi,

I am Anush. I am using rest services in my application. I am using services which are giving xml format output.
But i am unable to read the parameters from outside. Means from a jsp. Can u tell me how to read parameters from jsp and how to send if any types avialiable.

Please help me.

Thanks in advance.

deepak said...

Hello to all....
Can anybody knows about how to post the form date through the java web service.
Thanks in advance.....

Tim said...

For those trying to figure out where doa.Database is, it's in the downloadable Project Source files at the top of the page. Just extract that file to your dao package and you're good to go.

Anonymous said...

oauth with jersey ?

Anonymous said...

Jersey + spring ???????

Anonymous said...

HI thanks for the post can you please provide the dao.database file also ???

Anonymous said...

Thank your for sharing your knowledge.

shorav said...

Hi, I have a JAX-RS Restful webservice. This resource/webservice is asset for us. I am exposing this service url to third party client that would call this service resource. I want to protect this service from another authorised client/vendors.

Thus my question is -

How to protect this.

I thought to include an API key and the API key should be matched with a perticuler client API Key. And I also need to match the client url address means from whcih url the request is coming.

How to do this. How to get the URL that is calling the our rest service. I am deploying my rest in Tomcat 7.0.

Axelask said...

When I try to use POST method instead GET method, i always get "HTTP Status 405 - Method Not Allowed". Can anybody hel me?

Luillyfe punto psp said...

You have add follow the target,
com.sun.jersey.server.impl.container.servlet.ServletAdaptor


com.sun.jersey.config.property.packages
my.package.name


for work it

Dnyanesh said...

Really a nice article.
Can you please post similar article for PHP Rest API web service with MySQL as the database

Maheshwar Ligade said...

Hi friend i am creating webservice by refering your above code i want to access that service through my Android Application .
Plz Help me

Sri said...

Can you please tell me what is that Database class?

Anonymous said...

Where i run it?
CREATE TABLE `website` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text,
`description` text,
`url` text,
PRIMARY KEY (`id`)
);

Anonymous said...

Is this project using Maven or Ant ?

silviya rani said...

Hi sir,
This tutorial is helped me a lot...i want to read these table results from my ios app,,,,is that possible one?

Anonymous said...

Thanks Srinivas . it worked for me.

arun kumar said...

Hi ,anyone know
how can i connect Mysql database using angularJs via java code???

sanjeev kumar said...

sir please send program for insert query for this table..
CREATE TABLE nas (
id int(10) NOT NULL auto_increment,
nasname varchar(128) NOT NULL,
shortname varchar(32),
type varchar(30) DEFAULT 'other',
ports int(5),
secret varchar(60) DEFAULT 'secret' NOT NULL,
server varchar(64),
community varchar(50),
description varchar(200) DEFAULT 'RADIUS Client',
PRIMARY KEY (id),
KEY nasname (nasname)
);

Post a Comment