Home Backend Development PHP Tutorial php调用自各儿的java(转)

php调用自各儿的java(转)

Jun 13, 2016 am 11:03 AM
gt java nbsp php system

php调用自己的java(转)
-----------------------------推荐方法 : JavaBridge.jar

http://sourceforge.net/projects/php-java-bridge

http://mirror.optus.net/sourceforge/p/ph/php-java-bridge/php-java-bridge_5.2.2_j2ee.zip

最开始要装jdk这个就不用说了,我装的是java ee 5+jdk

1.把下载的php-java-bridge_5.2.2_j2ee.zip解压出来,里面有个JavaBridge.war 直接用winrar打开,到WEB-INF/lib/JavaBridge.jar 把这个jar包拷到 你的php目录的ext/下。

2.打开war包,里面有个java的文件夹,把他全部拷到你的PHP项目下,如/demo/java

3.目前的版本是VMBridge了,要php调用java类,要先启动JavaBridge,

命令行下调用java –jar JavaBridge.jar或者双击JavaBridge.jar,在弹出的窗口中选择监听端口8080

为了以后启动方便,我在ext/下新建了一个bat文件内容如下:

@echo off
start javaw -jar JavaBridge.jar

保存后,双击启动 会有一个提示框选择vmbridge port 默认8080,直接点ok就行了

4.在/demo/下新建test.php内容如下:


require_once("java/Java.inc");

header("content-type:text/html; charset=utf-8");
// get instance of Java class java.lang.System in PHP
$system = new Java('java.lang.System');
$s = new Java("java.lang.String", "php-java-bridge config...

");
echo $s;

// demonstrate property access
print 'Java version='.$system->getProperty('java.version').'
';
print 'Java vendor=' .$system->getProperty('java.vendor').'
';
print 'OS='.$system->getProperty('os.name').' '.
$system->getProperty('os.version').' on '.
$system->getProperty('os.arch').'
';

// java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',
"EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

print $formatter->format(new Java('java.util.Date'));
?>
5.启动apache,在浏览器中查看 http://localhost/demo/test.php

会看到如下信息:

php-java-bridge config...

Java version=1.6.0_10
Java vendor=Sun Microsystems Inc.
OS=Windows Vista 6.0 on x86
星期日, 十一月 23, 2008 at 4:31:49 下午 中国标准时间





-------自定义JAR

package ttt;
public class phptest{
    /**
    * A sample of a class that can work with PHP
    * NB: The whole class must be public to work,
    * and of course the methods you wish to call
    * directly.
    *
    * Also note that from PHP the main method
    * will not be called
    */

    public String foo;

    /**
    * Takes a string and returns the result
    * or a msg saying your string was empty
    */
    public String test(String str) {
        if(str.equals("")) {
            str = "Your string was empty. ";
        }
        return str;
    }

    /**
    * whatisfoo() simply returns the value of the variable foo.
    */
    public String whatisfoo() {
        return "foo is " + foo;
    }


    /**
    * This is called if phptest is run from the command line with
    * something like
    * java phptest
    * or
    * java phptest hello there
    */
    public static void main(String args[]) {
        phptest p = new phptest();

        if(args.length == 0) {
            String arg = "";
            System.out.println(p.test(arg));
        }else{
            for (int i = 0; i                 String arg = args[i];
                System.out.println(p.test(arg));
            }
        }
    }
}


生成为JAR,拷贝到D盘下。



/demo/index2.php

require_once("java/Java.inc");

java_require("D://1.jar");

$myj = new Java("ttt.phptest");
echo "Test Results are " . $myj->test("Hello World") . "";

$myj->foo = "A String Value";
echo "You have set foo to " . $myj->foo . "
\n";
echo "My java method reports: " . $myj->whatisfoo() . "
\n";

?>





在浏览器中查看 http://localhost/demo/index2.php







--------------------------------方法二:php_java.dll 需要配置php.ini,新版的php-java-bridge都没有dll文件



首先確定你的PHP和Apache伺服器及JDK(or JRE也可)都已安裝完成

上網下載php-java-bridge(自行找戴點 or http://sourceforge.net/project/showfiles.php?group_id=117793 )


將下載回來的 php-java-bridge解壓縮,解壓後資料匣裡會有一個JavaBridge.war,再同樣將這個JavaBridge.war解壓縮(win rar即可解)
解壓後可從 WEB-INF資料匣裡的cgi資料匣找到java-x86-windows.dll,及WEB-INF資料匣裡的lib資料匣找到JavaBridge.jar

將java-x86-windows.dll和JavaBridge.jar 複制到PHP的外掛資料匣(我這邊是C:/AppServphp/ext),並將java-x86-windows.dll改成php_java.dll

修改php.ini檔案

如果php.ini原本沒有以下內容,請自行加上,如果原本就有以下內容,請修改成如下[我使用的是JDK]
extension=php_java.dll
[Java]
;java.java = "C:\jdk1.6.0_13\bin\java"
java.class.path = "D:\php\ext\JavaBridge.jar;c:\myclasses"  c:\myclasses可自定义,用来存放自己写的JAVA文件
java.java_home = "C:\jdk1.6.0_13\jre"
java.library = "d:\jdk1.2.2\jre\bin\server\jvm.dll"
java.library.path = "D:\php\ext"

重新起動Apache,查看phpinfo

java
java support     Enabled
java bridge     3.0.8
java.java_home     C:\jdk1.6.0_13
java.java     C:\jdk1.6.0_13\bin\java
java.log_file    
java.log_level     no value (use backend's default level)
java.ext_java_compatibility     Off
java command     C:\jdk1.6.0_13\bin\java -Djava.library.path=D:\php\ext -Djava.class.path=D:\php\ext/JavaBridge.jar -Djava.awt.headless=true php.java.bridge.JavaBridge INET_LOCAL:0 2
java status     running
java server     9267



看倒數第二項 java status的狀態是不是not running (這是因為你沒有啟動JavaBridge.jar)。如果變成running
----如果没有启动则执行:
因為不可能每次開機都手動去啟動JavaBridge.jar

所以我們寫一個批次檔,內容如下

@echo off
start javaw -jar JavaBridge.jar

把它存成phpJavaBridge.bat,同樣放在PHP的外掛資料匣裡(這裡是C:AppServphpext)

把該檔建立捷徑,把建立好的捷徑放到啟動裡(這裡是C:Documents and SettingsAll Users「開始」功能表程式集啟動)

這樣一來,以後每次開機後就會自動啟動C:AppServphpext 資料匣裡的phpJavaBridge.bat



------------------------------簡單範例


$system=new Java('java.lang.System');

echo "java版本".$system->getProperty('java.version')."
";
echo "發行廠商".$system->getProperty('java.vendor')."
";
echo "作業系統版本".$system->getProperty('os.name')."
";
echo "java版本".$system->getProperty('os.version')."
";
echo "java版本".$system->getProperty('os.arch')."
";
?>
----------------------------------

或者在php-java-bridge中找到test.php,http://localhost/test.php查看效果



---------------------



$system=new Java("java.lang.System");
print "Java version=".$system->getProperty("java.version")."
";
?>


-------------------------------
[java]
extension=PHP_java.dll
java.library.path=c:webPHP4extensions
java.class.path="c:webPHP4extensionsjdk1.2.2PHP_java.jar;c:myclasses" 

  在PHP.INI中加入extension=PHP_java.dll,并在[java]中,设定好java.class.path,让它指向 PHP_java.jar,如果你使用新的JAVA类,你也应该存入这个路径,在这篇例子中,我们使用c:myclasses这个目录。

--------------------------------------------测试环境,创建如下PHP文件:
 

$system = new Java("java.lang.System");
print "Java version=".$system->getProperty("java.version")."
n";
print "Java vendor=".$system->getProperty("java.vendor")."

nn";
print "OS=".$system->getProperty("os.name")." ".
$system->getProperty("os.version")." on ".
$system->getProperty("os.arch")."
n";

$formatter = new Java("java.text.SimpleDateFormat","EEEE,
MMMM dd, yyyy 'at' h:mm:ss a zzzz");
print $formatter->format(new Java("java.util.Date"))."n";

?> 

  如果你正确安装了,你将会看到以下信息:

Java version=1.2.2
Java vendor=Sun Microsystems Inc.
OS=Windows 95 4.10 on x86
Wednesday, October 18, 2000 at 10:22:45 AM China Standard Time 



理解如何调用JAVA很重要,下一步我们就要创建自己的JAVA文件,让PHP来调用,JAVA文件的java.class.path很重要



------------------创建和使用你自己的JAVA类   [注意大小写]





创建你自己的 JAVA 类非常容易。新建一个 phptest.java 文件,将它放置在你的 java.class.path 目录下【 c:\myclasses】,文件内容如下:

public class phptest{
    /**
    * A sample of a class that can work with PHP
    * NB: The whole class must be public to work,
    * and of course the methods you wish to call
    * directly.
    *
    * Also note that from PHP the main method
    * will not be called
    */

    public String foo;

    /**
    * Takes a string and returns the result
    * or a msg saying your string was empty
    */
    public String test(String str) {
        if(str.equals("")) {
            str = "Your string was empty. ";
        }
        return str;
    }

    /**
    * whatisfoo() simply returns the value of the variable foo.
    */
    public String whatisfoo() {
        return "foo is " + foo;
    }


    /**
    * This is called if phptest is run from the command line with
    * something like
    * java phptest
    * or
    * java phptest hello there
    */
    public static void main(String args[]) {
        phptest p = new phptest();

        if(args.length == 0) {
            String arg = "";
            System.out.println(p.test(arg));
        }else{
            for (int i = 0; i                 String arg = args[i];
                System.out.println(p.test(arg));
            }
        }
    }
}

  创建这个文件后,我们要编译好这个文件,在 DOS 命令行使用 javac phptest.java 这个命令。

  为了使用 PHP 测试这个 JAVA 类,我们在web目录下创建一个 phptest.php 文件,内容如下:


$myj = new Java("phptest");
echo "Test Results are " . $myj->test("Hello World") . "";

$myj->foo = "A String Value";
echo "You have set foo to " . $myj->foo . "
\n";
echo "My java method reports: " . $myj->whatisfoo() . "
\n";

?>

  如果你得到这样的警告信息:java.lang.ClassNotFoundException error ,这就意味着你的 phptest.class 文件不在你的 java.class.path 目录下。

  注意的是 JAVA 是一种强制类型语言,而 PHP 不是,这样我们在将它们融合时,容易导致错误,于是我们在向JAVA传递变量时,要正确指定好变量的类型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678";

  这只是一个很小的例子,你可以创建你自己的 JAVA 类,并使用 PHP 很好的调用它!关键在于理解java.class.path目录的重要性。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles