RESTful Web Services API using Java and MySQL
Wall Script
Wall Script
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.
web notification

64 comments:

  1. post how to integrate oauth with jersey

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

    thanks

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

    ReplyDelete
  4. could make an example spring3 + mybatis3 + primefaces3,


    Thank!!!...

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

    ReplyDelete
  6. Yes it works with Tomcat also

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

    Not bad overall!

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

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

    ReplyDelete
  10. Very good work, thank you very much !

    Could you please also make one based on PHP?

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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.

    ReplyDelete
  13. 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 !...

    ReplyDelete
  14. 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??

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

    ReplyDelete
  16. Great work, I really apreceate it.

    ReplyDelete
  17. 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.

    ReplyDelete
  18. 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.

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

    ReplyDelete
  20. 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.

    ReplyDelete
  21. oauth with jersey ?

    ReplyDelete
  22. Jersey + spring ???????

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

    ReplyDelete
  24. Thank your for sharing your knowledge.

    ReplyDelete
  25. 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.

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

    ReplyDelete
  27. 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

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

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

    ReplyDelete
  30. Can you please tell me what is that Database class?

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

    ReplyDelete
  32. Is this project using Maven or Ant ?

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

    ReplyDelete
  34. Thanks Srinivas . it worked for me.

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

    ReplyDelete
  36. 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)
    );

    ReplyDelete
  37. java.lang.ClassNotFoundException: com.sun.jersey.server.impl.container.servlet.ServletAdaptor

    Someone can help me?

    ReplyDelete
  38. Sir Please give me a web service for login after successfull connection with ms sql db.
    Parameters like: &username=XXXXX&password=XXXXX&dbconnectionurl=XXXXXXX.
    Please help me it is my first tast in my new job.

    ReplyDelete
  39. Hi
    can you please post for angularjs with mysql. fetching data from mysql and use front end as angularjs.

    ReplyDelete
  40. any body can help database class i need ....with mysql

    ReplyDelete
  41. Here is Database class that is 'not' missing in the downloadable project.

    package 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;
    }
    }

    }

    ReplyDelete
  42. Great it works!!!, However I think you need to generate your own web.xml, by creating a dynamic web project in eclipse.

    ReplyDelete
  43. hi bro very much helped thank you so much..

    ReplyDelete
  44. Hello, where is the MySQL data connectivity with URL, USERNAME, PASSWORD?

    ReplyDelete
  45. Hi,

    This is harini can u plz tell me how to get json without using gson with list of object from database.

    ReplyDelete
  46. Hello...

    i follow step by step from you, but HTTP Status 404 - /RESTfulproject/

    ReplyDelete
    Replies
    1. I am also getting this response
      Failed to load resource: the server responded with a status of 404 (Not Found)

      Delete
  47. Hi
    I 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.

    ReplyDelete
    Replies
    1. First design your database tables, create RESTful apis for update statements.

      Delete
  48. Hi

    i follow step by step from you, but HTTP Status 404 - /RESTfulproject/
    why?

    ReplyDelete
  49. 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.

    ReplyDelete
    Replies
    1. you need to add another method to insert in ProjectManager Class , something similiar to below and call this from FeedService class @POST

      Database 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();

      Delete
  50. HTTP status-404
    resource not available error
    Can someone help?

    ReplyDelete
  51. After upgrade to java 8 and Tomcat 8, It is throwing error like 'TypeNotPresentException'. Please help me to resolve this. Thanks.

    ReplyDelete

mailxengine Youtueb channel
Make in India
X