如何使用php运行java代码(.class)并在同一网页上显示

nil*_*ils 5 html php java html5

我试图使用PHP脚本运行java程序.

首先,php显示一个表单,用户输入两个值:价格和销售税率.接下来,它提取值并将其传递给java程序(预编译为.class文件).

如果所有的java代码都工作,我不确定输出的打印位置.我的最终目标是在html页面中向用户显示结果.

我将文件内容上传到我的Web服务器并尝试从那里运行它.

更新:

如何使用shell_exec或exec来运行java代码?我需要将参数(price,salesTax)传递给shell_exec.返回的输出存储在哪里?

PHP代码:

> <?php
> 
> $salesTaxForm = <<<SalesTaxForm
> 
> <form action="SalesTaxInterface.php" method="post">
> 
>    Price (ex. 42.56):<br>
> 
>    <input type="text" name="price" size="15" maxlength="15"
> value=""><br>
> 
>    Sales Tax rate (ex. 0.06):<br>
> 
>    <input type="text" name="tax" size="15" maxlength="15"
> value=""><br>
> 
>    <input type="submit" name="submit" value="Calculate!">
> 
>    </form>
> 
> SalesTaxForm;
> 
> if (! isset($submit)) :
> 
>    echo $salesTaxForm;
> 
> else :    $salesTax = new Java("SalesTax");
> 
>    $price = (double) $price;    $tax = (double) $tax;
> 
>    print $salesTax->SalesTax($price, $tax);
> 
> endif;
> 
> ?>
Run Code Online (Sandbox Code Playgroud)

Java代码:

import java.util.*;
import java.text.*;

public class SalesTax {
public String SalesTax(double price, double salesTax) 
{

    double tax = price * salesTax;

    NumberFormat numberFormatter;

    numberFormatter = NumberFormat.getCurrencyInstance();

    String priceOut = numberFormatter.format(price);

    String taxOut = numberFormatter.format(tax);

    numberFormatter = NumberFormat.getPercentInstance();

    String salesTaxOut = numberFormatter.format(salesTax);

    String str = "A sales Tax of " + salesTaxOut +

                 " on " + priceOut + " equals " + taxOut + ".";

    return str;

    }

}
Run Code Online (Sandbox Code Playgroud)

小智 10

shell-exec执行传递给它的命令.要使用它,你必须向你的类添加一个Main方法,并在命令行中传递像参数这样的属性,所以最后它应该如下所示:

这是你必须在php上执行的代码

  $output = shell_exec('java SalesTax 10.0 20.0');
Run Code Online (Sandbox Code Playgroud)

在哪里销售税是你的java类,10.0是第一个参数,和20.0第二.

你的主要方法应该是这样的

public static void main(String args[]){
   double price = Double.valueOf(args[0]);
   double salesTax = Double.valueOf(args[1]);
   String output = SalesTax(price,salesTax);
   System.out.println(output);
}
Run Code Online (Sandbox Code Playgroud)

这是一个非常简单的实现,你仍然应该添加验证和其他一些东西,但我认为这是主要的想法.也许将它移植到php应该更容易.

我希望你觉得这很有帮助.:)