JSON Card -- Front

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-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 msg_id;
private String message;
private String user_id;

//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 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.

RESTful Web Services with input parameters

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 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″
}]
Enhanced by Zemanta

Leave a Reply

Your email address will not be published. Required fields are marked *