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`)
);
`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
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 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.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;
}
}
}
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;
}
}
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;
}
}
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
{
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 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)
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/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 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"
}]
"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"
}]
Next post I will explain friendly RESTful web services with path inputs parameters.
Wow!I like you Java tutorial.
ReplyDeleteDo you know a good and cheap Java hosting.
nice post dudeee...................
ReplyDeleteWhy not use out-of-the-box JSON conversion that Jersey does? Additional manual conversion to Strings is completely unnecessary in this example.
ReplyDeletegood
ReplyDeleteVery useful tutorial. But I can't find a cheap hosting with java activated
ReplyDeleteREST has had such a large impact on the Web that it has mostly displaced SOAP- and WSDL-based interface design because it's a considerably simpler style to use.
ReplyDeletesuper explanation dude
ReplyDeletesuper explanation it is very helpful for me
ReplyDeletethank you
thanks for tutorial I have a question except this
ReplyDeleteI have a webservice and it has a add method like below
public Integer add(int a,int b){
return a+b;
}
when I call this method and given (2,3) it return 5
and convert json it produce "5" is this correct output?
serviceAdd sAdd=new serviceAdd();
Integer result=sAdd.add(2,3);
Gson gson = new Gson();
String json=gson.toJson(result);
System.out.println(json);
output is "5" is it correct result ?
Excelente !
ReplyDeleteObrigado!
thank you!
Thank you Very much...
ReplyDeleteI'am searching for this from two days and finally got it from you.
I used this tutorial for accessing web services in Android.
Thank You once again.....
i am new to service and webservice..how can i start to learn writing the services.Please help me
ReplyDeleteGood example
ReplyDeletethnax it's very useful
ReplyDeletehow to created webservices?????
ReplyDeleteplease post the steps of creating webservices using same example in Net Beans IDEs.
As soon as possible.
how to created websevices using posted example???
ReplyDeletePlease post the steps of creating webservices.
As soon as possible.
where did you passed the driver name and url for the connection??
ReplyDeleteHi, everything works great!!! Great code. When I want to change GET to POST the code doesn't work, User_Id give me null value, can you help me.
ReplyDeletepublic String messageFeed(@FormParam("userId") String User_Id) {
System.out.println("userID > "+User_Id);
}
RESULT
userID > null
Thanks for posting man great tutorial
ReplyDeleteHow provide authentication to restful service and also authenticate using jquery or javascript
ReplyDeleteWhen i validated this link "http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds" in json validator (http://jsonlint.com/) showing error...
ReplyDeleteCan any let me know why??
thanks for post :)
ReplyDeletehow to pass javascript json variable in java restfull service..?
ReplyDeleteHi,
ReplyDeleteThank you for this tutorial,
If :
Final GET URL
http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds
.
where the userId param come from ?
Thanks
Its very useful to understand restful web service.
ReplyDeleteThanks
ReplyDeleteVery GOOD and understandable Tutorial
*** I'm Getting this common :
"SEVERE: The ResourceConfig instance does not contain any root resource classes"
Already trying this fix i found on other post but it doesn't work.
com.sun.jersey.config.property.packages
org.arpit.javapostsforlearning.webservices
=== Please look my web.xml
FirstProject
index.html
index.htm
index.jsp
ServletAdaptor
com.sun.jersey.server.impl.container.servlet.ServletAdaptor
com.sun.jersey.config.property.packages
vpsolucoes.htmlreader.service
1
ServletAdaptor
/REST/*
</web-app
Hi srinivas, I am trying to develop java code for searching the bugs in bugzilla using bugzilla rest api method(/search) the link for bugzilla rest api method is https://wiki.mozilla.org/Bugzilla:REST_API:Methods#Search_for_bugs_.28.2Fbug_GET.29. Can you let me know how can i develop java code for searching bugs with description as parameter.
ReplyDeleteHi,
ReplyDeleteThis is very useful for all.Thanks lot....
Final GET URL
http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds
The json result is not coming in browser panel, displaying only console.
How to get it in browser?
Thanks a lot Srinivas!
ReplyDelete
ReplyDeletePlease write one restful service to upload a file containing data to import into mysql server.