5

我正在尝试使用 php 脚本运行 java 程序。

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

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

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

更新:

如何使用 shell_exec 或 exec 运行 java 代码?我需要将参数(价格、销售税)传递给 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;
> 
> ?>

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;

    }

}
4

2 回答 2

10

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

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

  $output = shell_exec('java SalesTax 10.0 20.0');

SalesTax是您的 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);
}

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

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

于 2013-06-29T05:14:12.913 回答
0

我不是 PHP 专家,但有几种方法可以做到这一点:

因此,一旦您为服务器端的东西选择了路径,如果您想在不重新加载页面的情况下显示结果,您将需要使用一些 javascript 并且很可能是 somejQuery.ajax或 some jQuery('.target-area').load.

于 2013-06-29T00:12:34.113 回答