









Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Prepare-se para as provas
Estude fácil! Tem muito documento disponível na Docsity
Prepare-se para as provas com trabalhos de outros alunos como você, aqui na Docsity
Encontra documentos específicos para os exames da tua universidade
Prepare-se com as videoaulas e exercícios resolvidos criados a partir da grade da sua Universidade
Responda perguntas de provas passadas e avalie sua preparação.
Ganhe pontos para baixar
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
PHPwithJava
Tipologia: Notas de estudo
1 / 16
Esta página não é visível na pré-visualização
Não perca as partes importantes!










This article copyright Melonfire 2000−2002. All rights reserved.
Extending Yourself.............................................................................................................................................
Getting Started....................................................................................................................................................
Rank And File.....................................................................................................................................................
A Custom Job......................................................................................................................................................
Passing The Parcel..............................................................................................................................................
An Exceptionally Clever Cow..........................................................................................................................
Beanie Baby.......................................................................................................................................................
Using PHP with Java
i
PHP doesn't come with Java support turned on by default, so you'll need to recompile it to enable this support. You can do this by adding the "−−with−java" compile−time parameter to the PHP "configure" script. Note that you'll also need a copy of the latest JDK − you can get this from http://java.sun.com/ (the examples in this article use version 1.3.0 of the JDK).
If you're using Windows, you've already got a pre−built Java extension with your PHP distribution − all you need to do is enable it. First, make sure that your system's PATH variable includes the path to the JDK − this can easily be accomplished by altering the PATH variable in your "autoexec.bat" file.
Next, pop open the "php.ini" configuration file, and skip over all the cryptic configuration commands to the "Java" section. There, set values for the following variables:
java.library − this refers to the location of the Java Virtual Machine file (jvm.dll), usually located in the JRE directory;
java.library.path − this refers to the location of PHP's Java extension;
java.home − this refers to the JDK's "bin" directory;
java.class.path − this refers to the Java CLASSPATH, which contains your custom Java classes. You should make sure that this variable always includes the location of the "php_java.jar" file (usually the /java/ directory)
While you're editing this file, also drop by the "Windows Extensions" section of "php.ini" and uncomment the "php_java.dll" extension.
Finally, check to make sure that the file "php_java.dll" is in the /extensions/ sub−directory, restart your Web server, and you're ready to roll!
Getting Started 2
Let's begin with a simple example to verify that everything is working as advertised. This script uses built−in Java methods to check for the existence of a particular file on your system and display its size.
exists()) { echo "The file ". $fp−>getAbsolutePath(). " is ". $fp−>length()
. " bytes"; } else { echo "The file ". $fp−>getAbsolutePath(). " does not exist"; }
This is fairly simple, and should be clearly understandable to anyone who knows basic Java programming. The first line of the script instantiates an object of Java's File class, and stores it in the PHP variable $fp.
$fp = new Java("java.io.File", "/home/john/test.txt");
In case you're wondering, it's possible to pass parameters to the class constructor by specifying them as arguments when creating the object. In the example above, the second argument to the class constructor contains the location of the file to be displayed.
Once the object has been instantiated, it becomes possible to access the methods and properties of the Java class using regular OOP syntax.
if($fp−>exists()) { echo "The file ". $fp−>getAbsolutePath(). " is ". $fp−>length()
. " bytes"; } else { echo "The file ". $fp−>getAbsolutePath(). " does not exist"; }
Rank And File 3
Now, the example on the previous page used a built−in Java class to demonstrate PHP/Java connectivity. It's also possible to instantiate and use a custom Java class in a PHP script. I'll demonstrate this by encapsulating the functionality of the core File class in my own FileReader class.
Here's the code for my custom class:
import java.io.*;
public class FileReader {
public File LocalFile;
// set file location public void loadFile(String FileName) { LocalFile = new File(FileName); }
// return file size public long getFileSize() { return LocalFile.length(); }
// check if file exists public boolean FileExists() { return LocalFile.exists(); }
// return file path public String getFilePath() { return LocalFile.getAbsolutePath(); }
There's no rocket science here − this class is only a wrapper for core File class methods. However, it will serve to demonstrate the basics of using a custom Java class in a PHP script.
Now, compile the class, copy the compiled code to your Java CLASSPATH, and write a script to use it.
A Custom Job 5
loadFile("/home/john/test.txt");
if($myClass−>FileExists()) { echo "File size is ". $myClass−>getFileSize(). ""; echo "File path is ". $myClass−>getFilePath();
} else { echo "Sorry, the file ". $myClass−>getFilePath(). " could not be found"; }
This is similar to the first example, except that, this time, I've used my own custom Java class in the script. Once an instance of the class has been instantiated, class methods can be accessed in the normal manner.
Here's what the output looks like:
File size is 385 File path is /home/john/test.txt
Next up, passing one Java object to another.
Using PHP with Java
A Custom Job 6
This class uses a Writer object for script communication; this Writer object is instantiated via the setWriter() class method.
public void setWriter(Writer out) { this.out = out; }
Next, the class method reverse() accepts a string, reverses it and returns it via the Writer object.
public void reverse(String string) throws Exception { try { // reverse the string here char tempArray[] = new char[string.length()];
for (int i = 0; i < string.length(); i++) tempArray[i] = string.charAt(string.length() − i − 1); String reversedString = new String(tempArray); out.write(reversedString);
// snip }
Compile this class, copy it to your Java CLASSPATH, and write a simple PHP script to access it.
setWriter($writer); $obj−>reverse("The cow jumped over the moon");
Using PHP with Java
Passing The Parcel 8
echo $writer−>toString(); $writer−>flush(); $writer−>close();
?>
In this case, I've instantiated two objects, one for the ReverseString class and the other for the StringWriter class. Next, I've passed the StringWriter object, as stored in the PHP object $writer, to the ReverseString class via the class' setWriter() method, and then used the reverse() method to reverse a string and return the result.
Here's what the output looks like:
noom eht revo depmuj woc ehT
Using PHP with Java
Passing The Parcel 9
$obj = new Java("ReverseString");
// create an instance of the StringWriter object $writer = new Java("java.io.StringWriter");
// deliberately introduce an error by commenting out the next line // $obj−>setWriter($writer);
// suppress errors here @$obj−>reverse("The cow jumped over the moon");
// get the last exception $e = java_last_exception_get();
if ($e) { // print error echo $e−>toString(); } else { echo $writer−>toString(); $writer−>flush(); $writer−>close(); }
// clear the exception java_last_exception_clear(); ?>
Here's what the output looks like:
java.lang.Exception: Something really bad happened
Of course, this simple and graceful error message gets a little more unfriendly if you remove the @ error−suppression operator.
Warning: java.lang.Exception: Something really bad happened in /usr/local/apache/htdocs/java/exception.php on line 10 java.lang.Exception: Something really bad happened
Using PHP with Java
An Exceptionally Clever C... 11
Finally, how about connecting PHP up to a Java Bean? Here's the Bean, a simple Celsius−to−Fahrenheit−to−Celsius converter:
temperature.zip
The Bean exposes the following methods:
getCelsius() − get the current value of the Celsius property
getFahrenheit() − get the current value of the Fahrenheit property
setCelsius(num) − set the current value of the Celsius property to num
setFahrenheit(num) − set the current value of the Fahrenheit property to num
convertCelsiusToFahrenheit(value) − convert Celsius value to Fahrenheit
convertFahrenheitToCelsius(value) − convert Fahrenheit value to Celsius
And here's a PHP script which combines user input with the Temperature Bean to perform temperature conversion:
Temperature Converter setCelsius($temp);
// print result echo $myClass−>getCelsius()," o Celsius is ",$myClass−>convertCelsiusToFahrenheit($myClass−>getCelsius()),"
Beanie Baby 12
Once this form has been submitted, an object is instantiated from the Temperature class, and the information provided by the user is used to perform temperature conversion using the Bean methods described above. The result is then displayed to the user.
Here's what the result looks like:
Note that it's necessary to convert the type of the form variable $temp from string to integer in order to make it compatible with the arguments expected by the Bean − this data type conversion is one of the important issues you will face when accessing Java classes through PHP.
And that's about it for the moment. In case you'd like to learn more, take a look at the following links:
The PHP manual's Java pages, at http://www.php.net/manual/en/ref.java.php
O'Reilly's PHP and Java tutorial on O'Reilly ONLamp.com, at http://www.onlamp.com/pub/a/php/2001/06/14/php_jav.html
PHPBuilder's PHP and Java tutorial, at http://www.phpbuilder.com/columns/marknold20001221.php
See you soon! Note: All examples in this article have been tested on Linux/i586 with JDK 1.3.0, Apache 1.3.20 and PHP 4.1.1. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!
Using PHP with Java
Beanie Baby 14