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.
No comments:
Post a Comment