Develop with Java and PHP technology on AIX Version 5.3, Part 6: Building a PHP Web interface to the Java business application

Set up a PHP Web interface for a Java™ business application using the database created in earlier in this series (see Resources). The PHP Web interface collects information from users and sends the session data to the Java business application for processing and for a response.

Share:

Martin Brown (mc@mcslp.com), Freelance Writer, Freelance Developer

Martin Brown has been a professional writer for more than seven years. He is the author of numerous books and articles across a range of topics. His expertise spans myriad development languages and platforms—Perl, Python, Java™, JavaScript, Basic, Pascal, Modula-2, C, C++, Rebol, Gawk, Shellscript, Windows®, Solaris, Linux, BeOS, Mac OS X and more—as well as Web programming, systems management, and integration. He is a Subject Matter Expert (SME) for Microsoft® and regular contributor to ServerWatch.com, LinuxToday.com, and IBM developerWorks. He is also a regular blogger at Computerworld, The Apple Blog, and other sites. You can contact him through his Web site.



Doug Monroe (monroe@sqnt.com), System Administration Consultant, DMA Inc.

Doug Monroe is a UNIX System Administration consultant and instructor with DMA Inc. He holds a bachelor's degree in computer science from Oregon State University, and he has been supporting various flavors of UNIX since 1984. You can reach him at monroe@sqnt.com.



15 January 2008

Before you start

This tutorial is for AIX® 5.3 developers who want to get up to speed in integrating both PHP and Java™ technology in Web application development. In this tutorial, you will complete the process of building a solution that uses PHP for the front end to a back-end Java class for your Survey application. You'll also examine the differences between the Web service and PHP Java Bridge interfaces and the differences between PHP and Java development methods before examining the final solution for a PHP interface to your back end Java classes. You should have basic Java programming knowledge and basic Web development environment knowledge.

About this series

PHP is a top Web development language, and the Java language is popular for business application development. Thus, to use the strengths of each language on the AIX Version 5.3 operating system, the PHP Java Bridge has been developed. This series shows AIX 5.3 developers how to integrate both PHP and Java technology in their Web application development.

To demonstrate this, you will build a simple Survey application that follows a typical development process, including:

  • Developing the main Java application
  • Exposing the Java application through servlets as a Java-based Web application
  • Adding support for storing information within a database
  • Exposing the original application as Web service and providing a PHP interface to the application
  • Redeveloping the PHP interface using the dedicated PHP Java Bridge

The series is split into six parts:

  • Part 1 looks at the application and sets up an environment ready for building Java applications and serving Java-based Web applications using Tomcat.
  • Part 2 covers the main application code and the development of a simple Java Servlet to provide a Web interface to the information.
  • Part 3 connects the core application to a DB2® database for the storage of the survey questions and responses.
  • Part 4 converts the original application into one that can be accessed as a Web service, and it provides the base for the PHP interface.
  • Part 5 builds the PHP interface to the Java application by using the PHP Java Bridge.
  • Part 6 redevelops the application to make use of the PHP Java Bridge in place of the Web service interface.

About this tutorial

In this final tutorial of the series, you are going to look at using PHP and Java technology together to build a Web interface to your original Java classes that support the Survey application. This final solution uses the PHP Java Bridge to allow you to build a PHP-based interface to the Java classes developed in the first few parts of this series.

You are going to first look at the PHP Java Bridge and compare its operation to the Web service method that you originally developed, thus comparing the different technologies. Then you'll examine the different methods for integrating your PHP and Java-based solution before examining a final alternative for your PHP interface to the original Java class.

Prerequisites

You need the following software to follow along with this tutorial:


Comparing connection technologies

The Web service approach to your Survey application afforded you a great deal of flexibility and, in different ways, the PHP Java Bridge provides similar flexibility. Let's take a closer look at these differences and similarities before you delve deeper into the development process.

The Web service method

You converted the original application so that it could be accessed as a Web service in the fourth part of the series (see Resources). The Web service model has a number of advantages, not least of which is the accessibility. By exposing the classes through a Web service interface, you can guarantee interoperability, since nearly all languages support some form of Web service support—whether that is XML-RPC or Simple Object Access Protocol (SOAP).

The result is a lot of flexibility. Your Java back end can now be accessed by scripts and applications written in C, Perl, Java language, PHP, JavaScript, and many others; however, the interoperability comes at a cost.

As you saw in fourth installment of this series, exposing your applications as a Web service is hardly a trivial exercise. To do it right requires development and deployment of your code through a Web Services Description Language (WSDL) file; and then you have to separately define the interfaces to each function, while also ensuring that the encoding and encapsulation of supplied values and return values is in a format that is interoperable with the standards you want to use.

All of that work requires a significant amount of time to develop and, longer term, to keep in check as you develop and add new functionality and extensions to your core classes. It is probably not an overstatement to expect to add 25 to 50 percent of your development time for the original classes to make those same classes accessible through a Web service interface.

Furthermore, as you'll see in more detail later, the Web services option also implies a significant performance overhead that shouldn't be ignored if you expect to deploy your application in a large-scale operation.

The PHP Java Bridge

In the fifth installment of this series, you looked in detail at the PHP Java Bridge (see Resources), but the key element of the PHP Java Bridge allows you to access Java classes directly from within PHP, just as if you were accessing a local PHP class.

Although the Web service and PHP Java Bridge interfaces are very different in a fundamental way, in reality, they both communicate over XML to exchange the information about the original methods and classes and how they should be accessed. Unlike the Web service solution, the process is automatic.

As you saw in the fifth installment (see Resources) and as outlined here in Listing 1, once you have imported the PHP element and created the connection to the remote Java host, using and creating Java classes and objects is straightforward.

Listing 1. Simple PHP Java Bridge example
<?

require_once("http://sulaco.mcslp.pri:8080/JavaBridge/java/Java.inc");

$System = new Java("java.lang.System");

print_r($System->getProperties());

?>

You'll examine the exact methods and solutions required later in this tutorial.

Differences and similarities

The Web service and PHP Java solutions share a number of distinct differences and similarities that provide advantages and disadvantages on both sides of the development and deployment aspects of your application.

For example, both the Web service and PHP Java Bridge solutions enable you to use PHP for your front end and a Java environment for your back-end portions of the application. For the Web service solution, you must develop the original classes, the Web service classes, and the PHP interface. With the PHP Java Bridge, you need only to develop the original Java classes and the PHP front end—the PHP Java Bridge handles all of the interoperability issues for you.

A more significant difference between the Web service and PHP Java Bridge solution is the steps required to achieve the solution. The Web service solution requires additional development time to expose the services through the desired Web service interface and make them available. Using the Web service from within PHP is also comparatively non-trivial, as you must develop a solution that interfaces to the Web service interface that you have developed.

With the PHP Java Bridge, you can access the existing Java classes directly without having to explicitly develop an interface on the Java side or an access interface on the PHP side.

Performance

In order to convert your original request into something that is completely platform-neutral, one of the key problems with Web services is that the request must be converted into XML. The resulting XML packet includes the request, source or destination information, and any data or information contained in that request (for example, arguments to a method or function) and that makes the payload of the XML component quite large.

Generating valid XML in this way is quite time consuming, but decoding that information can be even more time consuming, as XML parsing is not as simple and straightforward a process as you might expect. The result is a comparatively high load on the client that sends the request to the server, then receives it, and finally processes the request. The same process happens in reverse (response encoded in XML, sent to client, client parses XML, and extracts response) when the response is sent back to the client.

You can see this in more detail in Figure 1.

Figure 1. The Web service interface in action
The Web service interface in action

The open format and encoding in XML is what makes Web services so compatible and accessible; however, it also places a significant load on both the client and server to have to create and parse XML just to exchange the information.

If you want to use Web services as your solution for exposing your Java application using PHP as the front end, keep in mind that the load on your Web server will be considerable, as you basically have to encode and decode the XML twice on the same machine.

By using the PHP Java Bridge, information is still encoded and even encoded in XML, but it is a much stricter and more easily encoded and decoded format than either SOAP or XML-RPC.

Java and PHP development

There are some important differences between the development of Java-based Web applications and PHP applications. It is worth considering these differences and how that can affect the development of your survey solution.

Java technology is a heavily object-based and class-based compiled language. As you've already seen with the Java language, you must edit the source code and then compile the source code into the final classes before you can use them.

PHP is an interpreted language, which means that you need only edit the source code and then access the PHP page to execute the program. This makes development of your application very quick, since you need to do very little to actually enable your application.

By default, PHP is not an object-oriented language, but it does support the notion of object orientation and you access properties and execute methods on an instance of a class. Within the Java environment, you access a method by separating the class instance and the method with a period:

surveyquestion.ashtml()

With PHP, you would use this line:

$surveyquestion->ashtml()

With the PHP Java Bridge, most PHP types are automatically converted into the corresponding Java types (and vice versa). There are some minor differences due to the differences in available types. For example, PHP has no concept of the Boolean data type used by the Java language. To exchange a Boolean data type between PHP and Java language, you have to create a new Boolean type with an integer for the value and then use that, as shown in Listing 2.

Listing 2. Creating a new Boolean type with an integer for the value
$boolean = new Java("java.lang.Boolean",1);        
print $question->htmlquestion($boolean);

Similarly with arrays, PHP does not natively support a bare array type (all arrays in PHP are maps), but you can simulate a Java array by using the PHP array() type to create a normal index-referenced array:

array("Red","Green","Blue")

You'll see some examples of these in action when you start to develop the final PHP interface later in this tutorial.


Developing a Web interface

With your original Java class, you developed a Java servlet solution that built on the Java classes, changing your original Java-based survey application from one that worked through a simple command-line text interface into a Web one. Now you are building an interface that uses a completely different language.

Revisiting the Web interface for the Java environment

The solution developed in the fourth installment of this series used the Servlet interface of the Tomcat deployment platform to provide an interface between the Java application and the HTML and HTTP interface that you wanted to present to users.

The outer wrapper, the WebSurvey class, was an extension of the original core Survey class that built a collection of SurveyQuestion objects using the different Survey classes, and then iterated over the individual question objects and called the askhtml() method to output the HTML directly to the Writer interface from the servlet classes.

The original servlet class, WebSurvey, generated a very simple form using a unified method across each SurveyQuestion class instance. Throughout, the method for generating the code was to explicitly print the various HTML elements. For reference, the original solution is shown here in Listing 3.

Listing 3. The Java Servlet survey builder
public void doGet(HttpServletRequest request,
                HttpServletResponse response)
  throws ServletException, IOException {

  PrintWriter out = response.getWriter();
  Integer formfieldid = 1;

  response.setContentType("text/html");

  out.println("<h1>Survey</h1>");
  out.println("<form action=\"/WebSurvey/survey\" method=\"POST\">");
    
  for(Iterator<SurveyQuestion> i = survey.iterator(); i.hasNext(); ) {
        SurveyQuestion question = (SurveyQuestion) i.next();
        question.askhtml(formfieldid,out);
        formfieldid++;
  }
    
  out.println("<input type=\"hidden\" name=\"highfieldid\" value=\
   \"" + survey.size() + "\">");
  out.println("<input type=\"submit\">");
  out.println("</form>");
}

This method generates some basic HTML by writing the output directly and then calls the askhtml() method for each SurveyQuestion class to output the HTML for the survey form.

Parsing the responses

For the submission of the survey data back to the client and insertion into the database, you created a simple wrapper method for the POST method type, as shown here in Listing 4.

Listing 4. Processing the responses
public void doPost(HttpServletRequest request,
                  HttpServletResponse response)
    throws ServletException, IOException {

    response.setContentType("text/html");
    ResultSet rs;
    Statement s;
    PreparedStatement ps;
    Integer responseid = -1;

    PrintWriter out = response.getWriter();

    out.println("<h1>Results</h1>");
    
    try {
        s = conn.createStatement();
        s.executeUpdate(
                        "INSERT INTO survey_response (responseid) "
                        + "values (0)",
                        Statement.RETURN_GENERATED_KEYS);
        
        rs = s.getGeneratedKeys();
        
        if (rs.next()) {
            responseid = rs.getInt(1);
        } else {
            System.out.println("Can't get auto incremement data");
            out.println("Sorry, we couldn't write your responses into the DB");
        }
        
        rs.close();
        s.close ();
    } catch (Exception ex) {
        System.out.println("SQLException (getting responseid): " + ex.getMessage());
    }

    Integer fieldid = 1;

    for(Iterator<SurveyQuestion> i = this.survey.iterator(); i.hasNext(); ) {
        SurveyQuestion question = (SurveyQuestion) i.next();
        question.showquestion(out,false);
        out.println("<p>" + request.getParameter("field" + fieldid));

        try {
            ps = conn.prepareStatement (
                                        "INSERT INTO survey_response_detail
                                        (responseid, question, 
                                        responsestring) VALUES(?,?,?)");
            ps.setString (1,responseid.toString());
            ps.setString (2,fieldid.toString());
            ps.setString (3,request.getParameter("field" + fieldid));
            int count = ps.executeUpdate ();
            ps.close ();
        } catch (Exception ex) {
            System.out.println("SQLException (adding question result): " 
			+ ex.getMessage());
        }       
        fieldid++;
    }
}

The process here is to get the unique ID from the database and then insert the rows into the response table based on the entries within the survey form.

To redeploy this in PHP, you have to reconsider this process slightly.

Re-deploying in PHP

With PHP applications, the Web application consists of a single page that is accessed by the Web client. Apache accepts the Web request, passes the processing of the page content to PHP, which then outputs the HTML elements verbatim and parses the PHP code to generate or process the necessary output.

In effect, a PHP page operates more like a JSP page, where the HTML that makes up the page and the PHP code are mixed into the same document.

When redeploying the application with PHP, there are a number of different solutions and alternatives available. For your current Java classes, you need to make a slight alteration so that you can integrate properly between PHP and the Java classes through the PHP Java Bridge.

In fact, there are a number of potential solutions that you can use:

  • To generate the HTML for the form, you can alter the Java code to return a pre-formatted version of the entire form in HTML with just one method call.
  • Or, you can output the HTML form for each individual question by calling a modified version of the HTML generators.
  • For parsing the response information, you need to modify the Java class to accept the individual response details. This needs to be handled directly by the Java class, because it is the Java class that provides the interface to the database.

Another alternative, not listed here, is that you can access the SurveyQuestion classes directly and then output the required HTML directly within PHP. This particular solution is less than ideal, because it actually eliminates one of the advantages of using the Java classes from PHP. However, in some applications and environments, direct access to Java class properties might be the appropriate solution.

Let's start by looking at the basic deployment alternatives.


Creating a PHP interface to the Java survey data

Now you know the different solutions available to you, so it's time to create some different solutions that use PHP on the front end and the core Java classes on the back end.

Creating a new instance of the Survey application

To create a new instance of the Survey application from within PHP with the PHP Java Bridge, you need to create an instance of the Survey application, or at least, create an instance of one or more of the SurveyQuestion classes.

The Java classes that you load must be made accessible to the Tomcat instance and the PHP Java Bridge. First, you need to create a JAR file with all the class files in it that you want to use:

$ jar cf survey.jar Survey*.class

Now you can copy the JAR file to a location where the Tomcat server can find the file when the PHP script requests to create a class based on the Java code. The PHP Java interface can load the JAR file and the classes from a variety of different places, including a local file or a URL.

You specify the JAR file requirement using the java_require() function within the PHP script. Interestingly enough, if you specify a file location, then the file location is the location on the remote server that is providing the PHP Java Bridge interface, not the machine on which the PHP script is being executed.

For example, the sample script in Listing 5 imports the PHP Java Bridge from a machine named Sulaco. It specifies the requirements for survey.jar which, in this case, has been copied into the /usr/share/java on the machine called Sulaco.

You then instantiate an instance of the SurveyQuestionText and call a new method you defined on that class called ashtml(), which returns a string containing the HTML for the question.

Listing 5. Importing the PHP/Java bridge
<?

try { require_once("http://sulaco.mcslp.pri:8080/JavaBridge/java/Java.inc"); }
        catch (JavaException $e) { echo "Couldn't load java",$e; }
try { java_require("/usr/share/java/survey.jar"); }
        catch (JavaException $e) { echo "Couldn't load class",$e; }
$question = new Java("SurveyQuestionText","Name","Enter your full name");
$boolean = new Java("java.lang.Boolean",1);
print $question->htmlquestion($boolean);
?>

If you access this PHP script, you should get the HTML-formatted text question for the SurveyQuestionText class instance created in the previous line.

Generating the Survey form through a single method

As you saw in the previous section, unlike the Web service solution where you had to expose specific classes and interfaces with the PHP Java Bride, you can automatically expose all your Java classes in their entirety.

This opens up a number of possibilities. With your original classes, they were developed for very specific environments—a command-line interface and through the servlets with an HTML interface, but both wrote the information directly to the appropriate interface.

When working with the PHP class, you either need to alter the Java classes to generate HTML and return the information as a string, or you need to access the properties of the Java class instance directly instead.

For the former solution, you can alter the Java classes just by creating an ashtml() method that returns the input field information. For example, Listing 6 shows a modified version of the SurveyQuestionText class.

Listing 6. Modified version of the SurveyQuestionText class
import java.io.*;
import java.util.*;

public class SurveyQuestionText extends SurveyQuestion { 

    public SurveyQuestionText(String qtext,
                              String qhelp) {
        this.question_text = qtext;
        this.question_help = qhelp;
        this.question_type = "text";
    }

    public void askspecific() {
        this.question_response.add(this.getresponse());
    };

    public String ashtml(Integer fieldid) {
        String qtext = this.questionhtml(true) +
            "<input type=\"text\" size=\"80\" name=\"field" + fieldid + "\"><br/>";
        return(qtext);
    }

}

Listing 7 shows the ashtml() method for the SurveyQuestionRadio method.

Listing 7. Exposing the survey question information as HTML
public String ashtml(Integer fieldid) {
        String qtext = "";

        qtext = qtext + this.questionhtml(true);

        for(Iterator<String> i = this.question_options.iterator(); i.hasNext(); ) {
            String option = i.next();
            qtext = qtext + "<input type=\"radio\" name=\"field" + fieldid + "\" 
			value=\"" +
                option + "\">" + option + "<br/>";
        }
        return(qtext);
    }

Note that in both examples you return a string of the information and, in both cases, you still have to supply a unique field ID to identify the field information, because it is the field ID that separates each field value when the HTML form is sent back.

For you to use this information through a single class, you need to create a new wrapper class, PHPSurvey, that creates the survey and then returns a pre-formatted HTML form ready for insertion into your PHP page. You can see this in Listing 8.

Listing 8. Building a new front end to the Survey classes
import java.io.*;
import java.util.*;

public class PHPSurvey {
    Collection<SurveyQuestion> survey = new ArrayList<SurveyQuestion>();

    public PHPSurvey () {
        survey.add(new SurveyQuestionText("Name",
                                          "Enter your full name"));
        survey.add(new SurveyQuestionRadio("Favourite colour",
                            "Enter your favourite colour",
                            new String[] {"Red", "Blue", "Green"}));
    }

    public String generate() {
        String surveyform = "";
        Integer count = 0;

        for(Iterator<SurveyQuestion> i = this.survey.iterator(); 
                i.hasNext(); ) {
            count++;
            SurveyQuestion question = (SurveyQuestion) i.next();
            String text = question.ashtml(count);
            surveyform = surveyform + text;
        }

        return (surveyform);

    }
}

Now you can access the entire class to get a single representation of the form, as generated by the back-end Java component, using the PHP in Listing 9. There's no additional dressing in this example; you just output a raw form to demonstrate how it works.

Listing 9. Accessing our Survey classes as PHP
<?

try { require_once("http://sulaco.mcslp.pri:8080/JavaBridge/java/Java.inc"); }
        catch (JavaException $e) { echo "Couldn't load java",$e; }
try { java_require("/usr/share/java/survey.jar"); }
        catch (JavaException $e) { echo "Couldn't load class",$e; }
$survey = new Java("PHPSurvey");
print $survey->generate();
?>

Creating and generating the survey in this way almost misses the point though—the PHP interface is doing very little and the back-end Java components are essentially still doing the work of presenting the survey information in a format that the user can use to submit the data. What you want to do is separate the presentation and the back-end components.

Generating the form by using SurveyQuestion methods directly

Because you can instantiate any Java class from within your PHP component using the PHP Java Bridge, there is no reason why you can't create your own survey directly within PHP.

The individual SurveyQuestion classes can all be used directly and you can access the different components of an instantiated class directly. At the simplest level, you can create the survey within PHP and then call the ashtml() to generate the code, as shown here in Listing 10.

Listing 10. A complete PHP survey
<html>
<head>
<title>Survey</title>
</head>
<body>
<h1>Please answer the following questions:</h1>
<form action="PHPJava4.php" method="POST">
<?

try { require_once("http://sulaco.mcslp.pri:8080/JavaBridge/java/Java.inc"); }
        catch (JavaException $e) { echo "Couldn't load java",$e; }
try { java_require("/usr/share/java/survey.jar"); }
        catch (JavaException $e) { echo "Couldn't load class",$e; }


$survey = array(
                new Java("SurveyQuestionText",
                         "Name","Enter your fullname"),
                new Java("SurveyQuestionRadio",
                   "Favorite color","What is your favorite color?",
                   array("Red","Green","Blue"))
                );

foreach ($survey as $i => $value) {
    print $survey[$i]->ashtml($i);
}

?>
<input type="submit">
</form>

This is a complete page and you can see the output here in Figure 2.

Figure 2. The HTML-base survey form
The HTML-base survey form

The execution process works by creating a PHP instance of the Java class for each question type. As you can see, you've created an identical survey to the one you generated within the Java native examples.

When creating the SurveyQuestionText type, the arguments supplied to the class instance creator are the survey question and the help text.

For the SurveyQuestionRadio, you have to supply the question and help text and then an array of values that form each radio button. You do this explicitly within PHP by creating a standard (non-associative) array using the PHP array() function.

In theory, you could access the class properties (question_text, question_help) directly, but as you've already mentioned, many applications using this method might defeat the object of using the PHP and Java interface. For this application and others, the Java classes should be the central version and the PHP merely an interface to it.

For your survey application, generating the HTML within the Java class is probably excessive and it places limitations on the formatting of the information. Accessing native Java properties from PHP for the original Java classes is not always possible, but for a simple text representation like the one required in your survey application, you could create some simple methods that returned the text property information when called.

The final part of your application is to submit the responses through the Java classes and into the database that will be used to store the information.

Submitting survey responses back to the Java classes

If you can create an instance of a SurveyQuestion class directly within PHP, then submitting the question responses back to the server is difficult without an additional function to determine the unique identifier that identifies this set of responses.

There a multitude of ways you can do this, including using the built-in PHP functions for session management. However, a simpler way is to use the code you developed when you added database support to the Java Servlets. In that example, you did the submission process all in one go, getting a unique ID from the database (by using an auto incrementing field to generate the ID) and then submitting the data into the survey_response_detail table.

You can make the system more flexible by defining two methods through the general PHPJava class, one to generate a unique ID and the other to write responses into the survey_response_detail table.

The unique survey response ID can be used either to populate a hidden field in the HTML form, or it could be used when the form is processed. You can see a modified version of the original method for the PHP Java class here in Listing 11.

Listing 11. Generating a unique ID for use in PHP through the Java interface
public Integer get_response_id () {
    ResultSet rs;
    Statement s;
    PreparedStatement ps;
    Integer responseid = -1;
    Connection conn = null;

    try {
        Class.forName("com.ibm.db2.jcc.DB2Driver");
        conn =
            DriverManager.getConnection("jdbc:db2://localhost:50000/SURVEY",
                                        "survey","surveypw");
    } catch (Exception ex) {
        System.out.println("SQLException: " + ex.getMessage());
    }

    try {
        s = conn.createStatement();
        s.executeUpdate(
                        "INSERT INTO survey_response (responseid) "
                        + "values (0)",
                        Statement.RETURN_GENERATED_KEYS);

        rs = s.getGeneratedKeys();

        if (rs.next()) {
            responseid = rs.getInt(1);
        } else {
            System.out.println("Can't get auto incremement data");
        }

        rs.close();
        s.close ();
    } catch (Exception ex) {
        System.out.println("SQLException (getting responseid): " + 
                           ex.getMessage());
    }
    return(responseid);
}

Within your PHP script, you can now obtain a unique ID by creating an instance of the class (if one does not already exist) and then call get_response_id(), as shown here in Listing 12.

Listing 12. Getting the unique ID in PHP
$survey = new Java("PHPSurvey");
$responseid = $survey->get_response_id();

Now with the unique ID, the only remaining process is writing the response into the table. For that, you need another method.

Submitting a survey response

Survey response information is inserted into the survey_response_detail table, which contains just three fields, the response ID (the unique value you obtained in the previous section), the field ID (the unique number added to each question within the survey), and the response itself.

To write this information into the database, you can use another method exposed through the PHPJava class that takes the three pieces of information as arguments and then writes that information into the database using a prepared statement. You can see the method here in Listing 13.

Listing 13. Saving responses into the database within Java
public void save_response(Integer responseid,
                          Integer fieldid,
                          String response) {

    Connection conn = null;
    PreparedStatement ps;

    try {
        Class.forName("com.ibm.db2.jcc.DB2Driver");
        conn =
            DriverManager.getConnection("jdbc:db2://localhost:50000/SURVEY",
                                        "survey","surveypw");
    } catch (Exception ex) {
        System.out.println("SQLException: " + ex.getMessage());
    }

   try {
        ps = conn.prepareStatement (
                                    
               "INSERT INTO survey_response_detail (responseid, 
									question, 
                responsestring) VALUES(?,?,?)");
        ps.setString (1,responseid.toString());
        ps.setString (2,fieldid.toString());
        ps.setString (3,response);
        int count = ps.executeUpdate ();
        ps.close ();
    } catch (Exception ex) {
        System.out.println("SQLException (adding question result): " + 
                           ex.getMessage());
    }
}

Note in the above method you open the connection each time a response is submitted, which would put a significant load on the process. This is unlike the Web service solution, where the potential exists to have to open the connection each time the response is submitted (since Web services are not persistent). With the PHP Java Bridge, you could put the initial connection and prepared statement construction into the instance method for the class. That would make the process significantly more efficient. An example of this is shown in Listing 14.

Listing 14. Using a persistent database connection for better performance
public class PHPSurvey {
    Collection<SurveyQuestion> 
    survey = new ArrayList<SurveyQuestion>();

    Connection conn = null;
    PreparedStatement ps;

    public PHPSurvey () {
        survey.add(new SurveyQuestionText("Name","Enter your full name"));
        survey.add(new SurveyQuestionRadio("Favourite colour",
                                           "Enter your favourite colour",
                                           new String[] {"Red", "Blue", "Green"}));

        try {
            Class.forName("com.ibm.db2.jcc.DB2Driver");
            conn =
                DriverManager.getConnection("jdbc:db2://localhost:50000/SURVEY",
                                            "survey","surveypw");
            ps = conn.prepareStatement (
                                        "INSERT INTO survey_response_detail " +
                                        "(responseid, question, responsestring)
                                        VALUES(?,?,?)");
        } catch (Exception ex) {
            System.out.println("SQLException: " + ex.getMessage());
        }
    }

...

public void save_response(Integer responseid,
                          Integer fieldid,
                          String response) {

    try {
        this.ps.setString (1,responseid.toString());
        this.ps.setString (2,fieldid.toString());
        this.ps.setString (3,response);
        int count = ps.executeUpdate ();
    } catch (Exception ex) {
        System.out.println("SQLException (adding question result): " + ex.getMessage());
    }
}

From the PHP side, you need to identify when the form has been submitted and then submit each response. Each field has the name 'field#', where # is the unique field number within the form as generated when each question was processed as HTML in the form. Once you've identified that the form has been submitted, you need only get a unique response ID, then iterate over each field in the response form, and call save_response() on your remote survey interface. Listing 15 shows this in practice, using the global PHPJava class and the generate() method to create the form.

Listing 15. Final PHP interface to the Java PHPSurvey class
<html>
<head>
<title>Survey</title>
</head>
<body>
<?

try { require_once("http://sulaco.mcslp.pri:8080/JavaBridge/java/Java.inc"); }
        catch (JavaException $e) { echo "Couldn't load java",$e; }
try { java_require("/usr/share/java/survey.jar"); }
        catch (JavaException $e) { echo "Couldn't load class",$e; }

$surveyint = new Java("PHPSurvey");

if (isset($_REQUEST['field0'])) {

    print "<h2>Submitting responses</h2>";

    $responseid = $survyeint->get_response_id();

    for ($i = 0;$i <= sizeof($survey);$i++) {
        if (isset($_REQUEST['field' . $i])) {
            print "Submitting response for field $i<br/>";
            $surveyint->save_response($responseid,$i,$_REQUEST['field' . $i]);
        }
    }
}
else {

    print "<h1>Please answer the following questions:</h1>";
    print '<form action="PHPJava5.php" method="POST">';

    print $surveyint->generate();

    print '<br/><input type="submit"/></form>';
}

?>
</body>
</html>

As you can see from this example, the PHP element is the display and process of the user interface information—the back-end Java class is still doing all of the work. This was always the plan: Get PHP to do the user interface elements while continuing to use the original Java classes to do the back-end work.


Summary

As you've seen in this tutorial, with a few relatively minor adjustments, you can alter your original Java classes to make them accessible through the PHP Java Bridge. The modifications don't change your original classes; in fact, you've created instances of the original classes directly within PHP. That, quite simply, is the power of the PHP Java Bridge solution.

With some additional modifications—mostly changing code you originally developed in earlier parts of the same series—you have been able to create a basic PHP-based interface to your original Java classes. The result is that you have a complete interface to the Java application directly from within PHP and with a much more flexible solution than with Web services. With Web services, you had to develop the interface that provided the same functionality.

Through this series, you've taken the original Java classes and actually changed the core elements (SurveyQuestion and the related SurveyQuestion* classes) very little. Through the process, you've added an interface to the database and developed a Web service solution to enable flexible access to the original classes. The result is a PHP-based interface to the original classes. You can use the same basic principles here in other applications to expose existing Java classes to a Web interface through PHP.

Resources

Learn

Get products and technologies

  • PHP: You can download PHP from the PHP website.
  • You can obtain the Apache httpd server from the Apache Web site.
  • NuSOAP: Learn more about this SOAP server and client library for PHP.
  • Tomcat: Download the latest package.
  • Java 5 64-bit SDK: You need to register to download this package, but registration is free.
  • Mozilla: The Mozilla Web browser for AIX can be downloaded from IBM.
  • Axis: This SOAP Web services toolkit is available from the Apache Web services site.
  • The Eclipse IDE can be obtained from the Eclipse Web site.
  • IBM trial software: Build your next development project with software for download directly from developerWorks.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into AIX and Unix on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=AIX and UNIX
ArticleID=281396
ArticleTitle=Develop with Java and PHP technology on AIX Version 5.3, Part 6: Building a PHP Web interface to the Java business application
publish-date=01152008