Tuesday, March 31, 2009

Creating The Web Services Client (Part 2)

The web services can be accessed by anykind of applications such as desktop application, web application, even mobile application. In the previous tutorial, we have learnt how to create a desktop application to access the web service. Now, we are going to create a web application with PHP to access that web service.

The Code

This is the PHP script. But, there is a requirement before you can run this script. You need a supporting library named NuSOAP. You can find it from www.sourceforge.net.

NuSOAP came in a zipped file. So, unzip it and copy the nusoap.php file to the same location with this script so it can be included with this script.

<html>
    <head><title>Web Service Client</title></head>
<body>
    <form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
        <input type="text" name="name"><input type="submit" name="submit" value="SUBMIT">
    </form>
    <div id="result" style="font-weight:bold;">
    <?php
    if($_POST['submit']){
        include("nusoap.php");
        
        // THE LOCATION OF WEB SERVICES
        $client=new soap_client("http://localhost:8080/axis/services");
        
        // CALL THE WEB SERVICE WITH THE METHOD NAME, INPUT PARAMETER, AND SERVICE NAME
        $result = $client->call('greeting', array("name" => $_POST['name']), 'helloService');
        if($client->getError()){
            echo $client->getError();
        }
        else{
            echo $result;
        }
    }
    ?>
    </div>
</body>
</html>

Run It!

This is the screenshot of this application while running.


Monday, March 16, 2009

Creating The Web Services Client (Part 1)

In the previous tutorial, we've learnt how to create a simple web service with Apache Axis. Now, we're going to learn how to create a simple client application to access that web service. This application is a simple desktop application made with Java programming language.

The Code

This is the source code of this application. Save this file with name helloClient.java

import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import javax.xml.namespace.QName;
import org.apache.axis.encoding.XMLType;
import javax.xml.rpc.ParameterMode;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class helloClient extends JFrame implements ActionListener{
    private JButton btnSend;
    private JTextField txtParameter;
    
    public void initComponent(){
        btnSend=new JButton("SEND");
        btnSend.setMnemonic('S');
        btnSend.addActionListener(this);
        txtParameter=new JTextField(10);
    }
    
    public void design(){
        setTitle("Web Service Client");
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(txtParameter);
        getContentPane().add(btnSend);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }
    
    private String sendRequest(String name) throws Exception{
        Service  service = new Service();
        Call call = (Call)service.createCall();
        String result;
        
        // SET THE LOCATION OF WEB SERVICE
        String endpoint = "http://localhost:8080/axis/services";
        call.setTargetEndpointAddress( new java.net.URL(endpoint));

        // SET THE SERVICE NAME AND THE METHOD TO BE CALLED
        call.setOperationName(new QName("helloService", "greeting"));
        
        // ADD THE INPUT PARAMETER
        call.addParameter( "name", XMLType.XSD_STRING, ParameterMode.IN );
        
        // SEND REQUEST TO WEB SERVICE
        String response = (String) call.invoke(new Object[]{name});

        return response;
    }
    
    helloClient(){
        initComponent();
        design();
    }
    
    public static void main(String [] args){
        new helloClient();
    }

    public void actionPerformed(ActionEvent ae){
        if(ae.getSource()==btnSend){
            try{
                JOptionPane.showMessageDialog(this,sendRequest(txtParameter.getText()), "Response", JOptionPane.INFORMATION_MESSAGE);
            }
            catch(Exception ex){
                JOptionPane.showMessageDialog(this,"Error : " + ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

Compile

This application needs some Axis' libraries. So, don't forget to set the required environment variables. I have write about this in the previous tutorial. After that, compile the helloClient.java file with this command.

javac -classpath %AXISCLASSPATH% helloClient.java

Run

If your compilation process didn't output any error, you can run this application with this command.

java -classpath .;%AXISCLASSPATH% helloClient

This is the screenshot of this application.


Monday, March 9, 2009

Creating Web Services With Apache Axis

The Environment Variables

Before you start, you have to set up some environment variables. You can set them from Windows System Properties or using the MS-DOS batch file (.bat)like this.

set AXIS_HOME=C:\apache-tomcat\webapps\axis\WEB-INF
set AXIS_LIB=%AXIS_HOME%\lib
set AXISCLASSPATH=%AXIS_LIB%\axis.jar;%AXIS_LIB%\commons-discovery-0.2.jar;%AXIS_LIB%\commons-logging-1.0.4.jar;%AXIS_LIB%\jaxrpc.jar;%AXIS_LIB%\log4j-1.2.8.jar;%AXIS_LIB%\saaj.jar;%AXIS_LIB%\wsdl4j-1.5.1.jar;%AXIS_LIB%\activation.jar;%AXIS_LIB%\mail.jar;%AXIS_LIB%\xmlsec.jar

If you are using Linux, you can use the following executable shell script (.sh) to set those environment variables.

#!/bin/sh
AXIS_HOME="/usr/local/apache-tomcat/webapps/axis/WEB-INF"; export AXIS_HOME;
AXIS_LIB="$AXIS_HOME/lib"; export AXIS_LIB;
AXISCLASSPATH="$AXIS_LIB/axis.jar:$AXIS_LIB/commons-discovery-0.2.jar:$AXIS_LIB/commons-logging-1.0.4.jar:$AXIS_LIB/jaxrpc.jar:$AXIS_LIB/log4j-1.2.8.jar:$AXIS_LIB/saaj.jar:$AXIS_LIB/wsdl4j-1.5.1.jar:$AXIS_LIB/activation.jar:$AXIS_LIB/mail.jar:$AXIS_LIB/xmlsec.jar"; export AXISCLASSPATH;

The Web Service

To create a web service with Apache Axis, you have to put all your code under webapps/axis/WEB-INF/classes folder. To make your project seems more organize, you can create one folder for each project. In this example I will create a folder named hello to store my files. And, this is the source code of helloService.java.

package hello;

public class helloService{
    public static String greeting(String name){
        return "Hello, " + name + "!";
    }
}

Compile it with this command.

javac helloService.java

Deploying Web Service

After compiling your web service, you need to deploy it. Before deploying it, you need to create a file called deploy.wsdd.

<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
    <service name="helloService" provider="java:RPC">
        <parameter name="className" value="hello.helloService"/>
        <parameter name="allowedMethods" value="*"/>
    </service>
</deployment>

Now, you can deploy it with this command (Don't forget to set the required environment variables before deploying it).

java -classpath %AXISCLASSPATH% org.apache.axis.client.AdminClient deploy.wsdd

Or with this command if you are using Linux.

java -classpath $AXISCLASSPATH org.apache.axis.client.AdminClient deploy.wsdd

Open the address http://localhost:8080/axis/services/helloService?wsdl with your web browser. This is the WSDL document of your helloService web service. If you see this, it means you have succesfully created your web service with Apache Axis.


Undeploying Web Service

To undeploy your web service, you have to create a file named undeploy.wsdd.

<undeployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
    <service name="helloService" />
</undeployment>

Undeploy it with this command (Once again, don't forget to set the required environment variables before undeploying it).

java -classpath %AXISCLASSPATH% org.apache.axis.client.AdminClient undeploy.wsdd

Or with this command if you are using Linux.

java -classpath $AXISCLASSPATH org.apache.axis.client.AdminClient undeploy.wsdd

Monday, March 2, 2009

Installing Apache Axis

Apache Axis is a very usefull software if you want to create web services with JSP. Apache Tomcat must be installed first if you want to install Apache Axis. In this tutorial, I assume you have installed Apache Tomcat. If you haven't installed Apache Tomcat, you can read my other tutorial about installing Apache Tomcat.

These are some steps for installing Apache Axis.

Supporting Libraries

Before installing Apache Axis, you also need these files as the supporting libraries.

  1. activation.jar
  2. mail.jar
  3. xmlsec.jar

Installing Apache Axis

  1. Download the latest version of Apache Axis from ws.apache.org/axis.
  2. Extract the axis-bin-1_4.zip in anywhere you like.
  3. Copy the axis folder inside the webapps folder of the Axis distribution folder, to your Apache Tomcat webapps folder.
  4. Extract those 3 supporting libraries and copy the .jar files to the lib folder inside the WEB-INF folder of your Axis installation folder.
  5. Start your Apache Tomcat or restart it if you've got it running.
  6. Access http://localhost:8080/axis. If you see the result like below this, it means you have installed Apache Axis successfully. You can also click the Validation link to check if your Axis' installation configuration is fine.

Sunday, February 8, 2009

Simple Database Application With JSP

This short tutorial will explain about creating a simple database application with JSP involving INSERT, UPDATE, DELETE, and also the SELECT process.

Preparing The Requirements

First, you need Apache Tomcat installed properly on you computer. I have written a tutorial about installing Apache Tomcat before this tutorial. You might want to read it first. Anyway, you also need to install MySQL as database server and the MySQL Connector for Java (available in .jar format) as the supporting library. You can search the MySQL Connector for Java with Google or find it at java.sun.com.

Copy your MySQL Connector JAR file to the lib folder under your Apache Tomcat installation directory. Then, restart your Apache Tomcat. Now, your Apache Tomcat is able to use that library.

Preparing Working Directory

Before you start to write your code, you might want to create a special folder to store all your projects. If you want it, you can create a folder under the webapps folder. In this example, I create a folder named work under the webapps folder to store my JSP files.

Creating The Database

Create a simple database with the following SQL command.

CREATE DATABASE db1;
USE db1;

CREATE TABLE item (
  id char(3) NOT NULL default '',
  name varchar(20) NOT NULL default '',
  price int(6) NOT NULL default '0',
  PRIMARY KEY  (`id`)
);

Creating The Database Class

For interacting with the database, I will make a special class. But first, you have to create some folders under your working directory with this structure.

  WEB-INF/
    classes/
      database/

And, this is the code for this class. Store it inside the database folder with name dbfunction.java.

package database;

import java.sql.*;

public class dbfunction{
 private Connection con;
 private Statement stat;
 private ResultSet result;
 
 public void createConnection(){
  try{
   Class.forName("com.mysql.jdbc.Driver");
   con=DriverManager.getConnection("jdbc:mysql://localhost/db1","user1","password");
  }
  catch(Exception ex){ }
 }

 public void createConnection(String driver, String url){
  try{
   Class.forName(driver);
   con=DriverManager.getConnection(url);
  }
  catch(Exception ex){ }
 }

 public void createConnection(String driver, String dataSource, String userName, String password){
  try{
   Class.forName(driver);
   con=DriverManager.getConnection(dataSource,userName,password);
  }
  catch(Exception ex){ }
 }

 public void closeConnection(){
  try{
   con.close();
  }
  catch(Exception ex){ }
 }

 public boolean updateRecord(String strSQL){
  try{
   stat=con.createStatement();
   
   int status=stat.executeUpdate(strSQL);
   if(status==1){
    return true;
   }
   else{
    return false;
   }
  }
  catch(Exception ex){
   return false;
  }
 }

 public ResultSet queryRecord(String strSQL){
  try{
   stat=con.createStatement();
   result=stat.executeQuery(strSQL);
   return result;
  }
  catch(Exception ex){
   return null;
  }
 }
}

Compile it.

javac dbfunction.java

The Application

Now, this is the time to create the main application. This application consists of three pages such as index.jsp, insert.jsp, and update.jsp. Save all those files inside your working directory.

index.jsp

This is the front page for displaying the records of the item table. It also has two links in each row for updating and deleting record. And, this is the code of this file.

<%@ page import="java.sql.*" %>
<html>
<head>
<script language="javascript" type="text/javascript">
 function confirmDelete(url){
  if(confirm("Are you sure want to delete this record?")){
   location.href=url;
  }
 }
</script>
<title>Viewing Table</title>
</head>
<body>
<jsp:useBean id="dbfunc" scope="page" class="database.dbfunction" />
<center>
<%
try{
 dbfunc.createConnection();

 if(request.getParameter("delete")!=null){
  if(dbfunc.updateRecord("DELETE FROM item WHERE id='" + request.getParameter("delete") + "'"))
   out.println("<p><b>Deleting record success!</b></p>");
  else
   out.println("<p><b>Deleting record failed!</b></p>");
 }

 ResultSet rs=dbfunc.queryRecord("SELECT * FROM item");

 out.println("<table border='1'>");
 out.println("<tr><th>Item ID</th><th>Item Name</th><th>Unit Price</th><th colspan='2'>&nbsp;</th></tr>");
 while(rs.next()){
  out.println("<tr><td>" + rs.getString("id") + "</td><td>" + rs.getString("name") + "</td><td>" + rs.getString("price") + "</td><td><a href='update.jsp?id=" + rs.getString("id") + "'>Update</a></td><td><a href=javascript:confirmDelete('index.jsp?delete=" + rs.getString("id") + "')>Delete</a></td></tr>");
 }
 out.println("</table>");
 out.println("<br>");
 out.println("<a href='insert.jsp'>INSERT RECORD</a>");

 dbfunc.closeConnection();
}
catch(Exception ex){
 out.println("<p><b>" + ex.toString() + "</b></p>");
}
%>
</center>
</body>
</html>

insert.jsp

This page is for inserting the record to the item table.

<html>
<head><title>Inserting Record</title></head>
<body>
<center>
<jsp:useBean id="dbfunc" scope="page" class="database.dbfunction" />
<%
if(request.getParameter("insert")!=null){
 try{
  dbfunc.createConnection();

  if(dbfunc.updateRecord("INSERT INTO item VALUES ('" + request.getParameter("itemId") + "', '" + request.getParameter("itemName") + "', '" + request.getParameter("unitPrice") + "')"))
   out.println("<p><b>Inserting record success!</b></p>");
  else
   out.println("<p><b>Inserting record failed!</b></p>");

  dbfunc.closeConnection();
 }
 catch(Exception ex){
  out.println("<p><b>" + ex.toString() + "</b></p>");
 }
}
%>
<form action="insert.jsp" method="POST">
<table>
<tr><td>Item ID</td><td>:</td><td><input type="text" name="itemId" size="10"></td></tr>
<tr><td>Item Name</td><td>:</td><td><input type="text" name="itemName" size="25"></td></tr>
<tr><td>Unit Price</td><td>:</td><td><input type="text" name="unitPrice" size="15"></td></tr>
</table>
<br>
<input type="submit" name="insert" value="INSERT">
</form>
<br>
<a href="index.jsp">VIEW TABLE</a>
</center>
</body>
</html>

update.jsp

This page is for inserting the record to the item table.

<%@ page import="java.sql.*" %>
<html>
<head><title>Updating Record</title></head>
<body>
<jsp:useBean id="dbfunc" scope="page" class="database.dbfunction" />
<center>
<%
try{
 ResultSet rs=null;

 dbfunc.createConnection();

 if(request.getParameter("update")!=null){
  if(dbfunc.updateRecord("UPDATE item SET id='" + request.getParameter("itemId") + "',  name='" + request.getParameter("itemName") + "', price='" + request.getParameter("unitPrice") + "' WHERE id='" + request.getParameter("id") + "'"))
   out.println("<p><b>Updating record success!</b></p>");
  else
   out.println("<p><b>Updating record failed!</b></p>");
 }

 if(request.getParameter("id")!=null)
  rs=dbfunc.queryRecord("SELECT * FROM item WHERE id='" + request.getParameter("id") + "'");

 if(rs.next()){
%>
  <form action="update.jsp?id=<%= rs.getString("id") %>" method="POST">
  <table>
  <tr><td>Item ID</td><td>:</td><td><input type="text" name="itemId" value="<%= rs.getString("id") %>" size="10"></td></tr>
  <tr><td>Item Name</td><td>:</td><td><input type="text" name="itemName" value="<%= rs.getString("name") %>" size="25"></td></tr>
  <tr><td>Unit Price</td><td>:</td><td><input type="text" name="unitPrice" value="<%= rs.getString("price") %>" size="15"></td></tr>
  </table>
  <br>
  <input type="submit" name="update" value="UPDATE">
  </form>

<%
 }

 dbfunc.closeConnection();
}
catch(Exception ex){
 out.println("<p><b>" + ex.toString() + "</b></p>");
}
%>
<br>
<a href="index.jsp">VIEW TABLE</a>
</center>
</body>
</html>

Screenshots

These are the screenshots when the application was being run.

  1. Inserting record.
  2. Viewing record.
  3. Deleting record.


  4. Updating record.