How to Create, Consume/Call and Test Restful Web-services in Java

Desired Output:

O/P if data exist
Click To Zoom


























O/P if data does not exist
Click to Zoom






















Download Rest webservices in java from here or here


Project Structure:

Click Image to zoom






















RESTfulClient_Jersey.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package client;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;


public class RESTfulClient_Jersey extends HttpServlet {
 private static final long serialVersionUID = 1L;
 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String output="";
   try {
       
    String a=request.getParameter("userName");
   
            Client client = Client.create();  
            WebResource resource = client.resource("http://localhost:8090/RestJaxB_Jersey_Client/rest/customers/"+a);  
            ClientResponse response_data = resource.accept("application/json").get(ClientResponse.class);
            //ClientResponse  response_data = resource.accept("application/xml").get(ClientResponse.class);// for xml response
          
            if(response_data.getStatus() == 200){
              
                output = response_data.getEntity(String.class);
                System.out.println(output);  
              
            }else System.out.println("Somthing went wrong..!");      
  
          } catch (Exception e) {  
                  e.printStackTrace();  
          }
          response.setContentType("text/plain");
          response.getWriter().write(output);
  
 }


}

Note: (1) localhost:8090 has been used.
          (2) RESTfulClient_Jersey.java is the file we call from index.jsp / jquery


RESTfulClient.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 package client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class RESTfulClient {
    
    public static void main(String[] Java4s) {
        
        try {
         int a=1;
            Client client = Client.create();    
            WebResource resource = client.resource("http://localhost:8090/RestJaxB_Jersey_Client/rest/customers/"+a);    
            ClientResponse response = resource.accept("application/json").get(ClientResponse.class);
          //ClientResponse response = resource.accept("application/xml").get(ClientResponse.class);// for xml response           
            if(response.getStatus() == 200){
                
                String output = response.getEntity(String.class);
                System.out.println(output);    
                
            }else System.out.println("Somthing went wrong..!");        
    
          } catch (Exception e) {    
                  e.printStackTrace();    
          }
    
        }   
}


Note: (1) localhost:8090 has been used.
          (2) For RESTfulClient.java o/p will be displayed in console.

Pojo_JaxB.java 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.businessLogic.rest;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "ClientInfo")
public class Pojo_JaxB {
 
 int id;
 String client_id;
 
 @XmlElement
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 
 @XmlElement
 public String getClient_id() {
  return client_id;
 }
 public void setClient_id(String client_id) {
  this.client_id = client_id;
 }
 @Override
 public String toString() {
  return "FetchInXmlPOJO [id=" + id + ", client_id=" + client_id
    + ", getId()=" + getId() + ", getClient_id()=" + getClient_id()
    + "]";
 }
 

}


Restful_Json_Xml.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 package com.businessLogic.rest;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import package_dal.Clsdal;
@Path("/customers")
public class Restful_Json_Xml {
    
    @GET
    @Path("/{cusNo}")
    @Produces("application/xml,application/json")
    //@Produces(MediaType.APPLICATION_JSON)
    public Pojo_JaxB produceCustomerDetailsinJSON(@PathParam("cusNo") int cusNo) throws ClassNotFoundException, SQLException {
        
     Clsdal obj_clsdal=new Clsdal();
     obj_clsdal.connect();
     String connectionURL ="jdbc:mysql://localhost/jaxb_restwebservice";
     String UID="root";
     String pwd="root";
     Connection con=DriverManager.getConnection(connectionURL,UID,pwd); 
     ResultSet rs=null;
          
     String query = "select ID,client_id from details where ID='"+cusNo+"'";
     

        PreparedStatement st = con.prepareStatement(query);
        rs = st.executeQuery();
  
        Pojo_JaxB obj=new Pojo_JaxB();
      while(rs.next())
       {
       
        obj.setId(rs.getInt("id"));
        obj.setClient_id(rs.getString("client_id"));
       }    
    
        return obj;
        
    }
}


Note: @Produces("application/xml,application/json") gives response in XML or JSON

Clsdal.java


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package package_dal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Clsdal {
    
 //to establish connection sql server
 
 //public String connectionURL ="jdbc:sqlserver://192.168.15.166;databaseName=oftraining";
 //public String classforname="com.microsoft.sqlserver.jdbc.SQLServerDriver";

 public String connectionURL ="jdbc:mysql://localhost/jaxb_restwebservice";
 public String classforname="com.mysql.jdbc.Driver"; 
     
 
 public String UID="root";
 public String pwd="root";
 Connection con;
  public Clsdal(){  
   super();    
 }

  public boolean connect() throws ClassNotFoundException,SQLException{ 
  Class.forName(classforname); 
  con = DriverManager.getConnection(connectionURL,UID,pwd); 
    return true; 
  } 

  public void close() throws SQLException{ 
   con.close(); 
   }

    public ResultSet executeSQL(String sql) throws SQLException{
  Statement s = con.createStatement(); 
  ResultSet r = s.executeQuery(sql); 
  return (r == null) ? null : r; 
  }

  public int updateSQL(String sql) throws SQLException{   
   Statement s = con.createStatement();
   int r = s.executeUpdate(sql);
   return (r == 0) ? 0 : r; 
  }
 }


Example2.js


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function Example2() {

 var value = document.getElementById("userName").value;
 var url = "RESTfulClient_Jersey";
 alert("url : " + url);
 var parameter = value;
 alert("parameter : " + parameter);
 var r = doPostAjax(url, parameter); // do not use alert(r);
 displayData(r);

}

function doPostAjax(url, parameter) {

 alert("doPostAjax ");

 return ($.ajax({
  url : url,
  type : "POST",
  async : false,
  data : "userName=" + parameter + "&userName2=" + "rahul",
  success : function(response) {
   ajaxResponse = response;
   //document.getElementById('ajaxResponse').value = response;
  }
 // other properties
 }));
}

function displayData(x) {
 x.success(function(realData) {
  $('#ajaxResponse').text(realData).css({
   color : 'green'
  });

  var json = realData, obj = JSON.parse(json);

  alert("client_id:  " + obj.client_id);
  alert("id:  " + obj.id);

  var a = obj.client_id;
  var b = obj.id;

  if (a != undefined) {
   $('#afterParsing').text("client_id: " + a + " and id : " + b).css({
    color : 'blue'
   });
   $('#data').val("client_id: " + a + " and id : " + b).css({
    color : 'green'
   });

  }

  else {
   $('#afterParsing').text("This data does not exist").css({
    color : 'red'
   });
   $('#data').val("This data does not exist").css({
    color : 'red'
   });
  }

 });
}



web.xml


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
    <servlet-name>JerseyRESTService</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
      <param-name>com.sun.jersey.config.property.packages</param-name>
      <param-value>com.businessLogic.rest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>JerseyRESTService</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
  
  
   <servlet>
    <servlet-name>RESTfulClient_Jersey</servlet-name>
    <servlet-class>client.RESTfulClient_Jersey</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RESTfulClient_Jersey</servlet-name>
    <url-pattern>/RESTfulClient_Jersey</url-pattern>
  </servlet-mapping>
</web-app>



index.jsp


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Rest call using Jquery Ajax</title>
<script type="text/javascript" src="js/Example2.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"
 type="text/javascript"></script>
</head>
<body>
 <form>

  AJAX implementation in JSP and Servlet using JQuery <br />
  <br /> Enter ID: <input type="text" id="userName" onblur='Example2()' />


  <br /> <br /> <br /> <br /> Response from jQuery Ajax Request on
  Blur event
  <div id="ajaxResponse"></div>


  <br /> <br /> <br /> <br /> Parsed json values
  <div id="afterParsing"></div>

  <br /> <br /> <br /> <br /> Data:<input type="text" id="data">

 </form>
</body>
</html>


Explanation:
Flow: index.jsp--> js/Example2.js--> RESTfulClient_Jersey.java--> back to index.jsp

Note:
(1) In Pojo_JaxB.java I have used annotations for elements hence we
   1) Get xml tags if o/p is in xml
   2) Get json Name and Value pair



(2)In RESTfulClient_Jersey.java or RESTfulClient.java we have
ClientResponse response = resource.accept("application/json").get(ClientResponse.class);
This tells application to accept json values. To accept xml, replace json to xml.




(3)In Restful_Json_Xml.java we have

@Produces("application/xml,application/json")
This tells application to give reponse either in xml or json depending upon request made from client.



(4) In RESTfulClient_Jersey.java we have
http://localhost:8090/RestJaxB_Jersey_Client/rest/customers

here,
http://localhost:8090/RestJaxB_Jersey_Client----> is project path
/rest/----> is defined in web.xml
/customers----> is path defined in Restful_Json_Xml.java



Click to Zoom

No comments:

Post a Comment