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`)
);
`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
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.
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.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;
}
}
}
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;
}
}
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;
}
}
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")
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>
<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"
}]
"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.
post how to integrate oauth with jersey
ReplyDeletethanks
ReplyDeleteHi man, Thanks for all your postings... Please post how to create a toolbar for all web browsers.
ReplyDeletethanks
Good!
ReplyDeleteخوبه !
Wow! Very good article.
ReplyDeleteWhat minimum version of JEE is required and it works with any application server? Tomcat?
Thanks For sharing this post :)
ReplyDeletecould make an example spring3 + mybatis3 + primefaces3,
ReplyDeleteThank!!!...
Please post on how to create the same with php. and how to communicate via soap messages.
ReplyDeleteYes it works with Tomcat also
ReplyDeleteYou may want to close you connection :). Perhaps too many concepts at once, and too much detail.
ReplyDeleteNot bad overall!
I think DTO stands for data transfer object... Am I wrong???
ReplyDeleteIts quite a good article..:) which just refreshed my REST Work sometime back..Thanks
ReplyDeleteVery good work, thank you very much !
ReplyDeleteCould you please also make one based on PHP?
In response to my previous message for a version on PHP : you already did it !
ReplyDeletehttp://www.9lessons.info/2012/05/create-restful-services-api-in-php.html
Thanks a lot for all your work
nice work . I like it
ReplyDeleteWhat'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.
ReplyDeleteHi Srininvas,
ReplyDeletePlease 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 !...
Hello PLease clarify me here -
ReplyDeleteDatabase 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??
I think DataBase class is in the dao package that is not available in the example program. Please check it.
ReplyDeleteGreat work, I really apreceate it.
ReplyDeleteGreat Work!!!!
ReplyDeleteawesome..really nice
ReplyDeleteHi Srinivas,
ReplyDeleteI 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.
Hi,
ReplyDeleteI 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.
Hello to all....
ReplyDeleteCan anybody knows about how to post the form date through the java web service.
Thanks in advance.....
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.
ReplyDeleteoauth with jersey ?
ReplyDeleteJersey + spring ???????
ReplyDeleteHI thanks for the post can you please provide the dao.database file also ???
ReplyDeleteThank your for sharing your knowledge.
ReplyDeleteHi, 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.
ReplyDeleteThus 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.
When I try to use POST method instead GET method, i always get "HTTP Status 405 - Method Not Allowed". Can anybody hel me?
ReplyDeleteYou have add follow the target,
ReplyDeletecom.sun.jersey.server.impl.container.servlet.ServletAdaptor
com.sun.jersey.config.property.packages
my.package.name
for work it
Really a nice article.
ReplyDeleteCan you please post similar article for PHP Rest API web service with MySQL as the database
Hi friend i am creating webservice by refering your above code i want to access that service through my Android Application .
ReplyDeletePlz Help me
Can you please tell me what is that Database class?
ReplyDeleteWhere i run it?
ReplyDeleteCREATE TABLE `website` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` text,
`description` text,
`url` text,
PRIMARY KEY (`id`)
);
Is this project using Maven or Ant ?
ReplyDeleteHi sir,
ReplyDeleteThis tutorial is helped me a lot...i want to read these table results from my ios app,,,,is that possible one?
Thanks Srinivas . it worked for me.
ReplyDeleteHi ,anyone know
ReplyDeletehow can i connect Mysql database using angularJs via java code???
sir please send program for insert query for this table..
ReplyDeleteCREATE 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)
);
very easy to follow
ReplyDeletejava.lang.ClassNotFoundException: com.sun.jersey.server.impl.container.servlet.ServletAdaptor
ReplyDeleteSomeone can help me?
Sir Please give me a web service for login after successfull connection with ms sql db.
ReplyDeleteParameters like: &username=XXXXX&password=XXXXX&dbconnectionurl=XXXXXXX.
Please help me it is my first tast in my new job.
Hi
ReplyDeletecan you please post for angularjs with mysql. fetching data from mysql and use front end as angularjs.
any body can help database class i need ....with mysql
ReplyDeleteHere is Database class that is 'not' missing in the downloadable project.
ReplyDeletepackage dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
public Connection Get_Connection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/workingbrain";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "");
return connection;
}
catch (SQLException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
}
Great it works!!!, However I think you need to generate your own web.xml, by creating a dynamic web project in eclipse.
ReplyDeletehi bro very much helped thank you so much..
ReplyDeletegreat work bro... :)
ReplyDeleteHello, where is the MySQL data connectivity with URL, USERNAME, PASSWORD?
ReplyDeleteHi,
ReplyDeleteThis is harini can u plz tell me how to get json without using gson with list of object from database.
FeedObjects cannot be resolved?
ReplyDeleteHello...
ReplyDeletei follow step by step from you, but HTTP Status 404 - /RESTfulproject/
I am also getting this response
DeleteFailed to load resource: the server responded with a status of 404 (Not Found)
Hi
ReplyDeleteI wanted to create simple web site using java which is facebook like.User can create posts in their wall . He/she invites other users to like his/her post comment give stars . All this information along with comment,starts will be stored in mysql database. after some time user can review his/her post how many stars likes he got.
First design your database tables, create RESTful apis for update statements.
DeleteHi
ReplyDeletei follow step by step from you, but HTTP Status 404 - /RESTfulproject/
why?
post annotation is not working, it shows a blank page and not able to insert values into database, can u please show crud operations using the same example.
ReplyDeleteyou need to add another method to insert in ProjectManager Class , something similiar to below and call this from FeedService class @POST
DeleteDatabase database= new Database();
String sql="insert into website(title,description,url) values (?,?,?)";
Connection connection = database.Get_Connection();
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1,feedobjects.getTitle() );
ps.setString(2,feedobjects.getDescription());
ps.setString(3,feedobjects.getUrl());
ps.executeUpdate();
ps.close();
HTTP status-404
ReplyDeleteresource not available error
Can someone help?
After upgrade to java 8 and Tomcat 8, It is throwing error like 'TypeNotPresentException'. Please help me to resolve this. Thanks.
ReplyDeletewow nice
ReplyDeleteThanks.