php - PHP 是否具有与 Java 的 RequestDispatcher.forward 等效的功能?

标签 php jsp http forwarding

在 Java 中,我可以编写一个非常基本的 JSP index.jsp像这样:

<% request.getRequestDispatcher("/home.action").forward(request, response); %>

这样做的效果是用户请求 index.jsp (或者假设 index.jsp 是该目录的默认文档的包含目录)将看到 home.action没有浏览器重定向,即 [forward]( http://java.sun.com/javaee/5/docs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)) 发生在服务器端。

我可以用 PHP 做类似的事情吗?我怀疑可以配置 Apache 来处理这种情况,但由于我可能无法访问相关的 Apache 配置,所以我会对单独依赖 PHP 的解决方案感兴趣。

最佳答案

Request.Forward 的诀窍在于它为您提供了一个干净的新请求,可以执行您想要的操作。因此,您没有当前请求的剩余部分,例如,依赖于 $_SERVER['REQUEST_URI'] 的 java eq 的脚本没有问题。

您可以放入一个 CURL 类并编写一个简单的函数来执行此操作:

<?php 
/**
 * CURLHandler handles simple HTTP GETs and POSTs via Curl 
 * 
 * @author SchizoDuckie
 * @version 1.0
 * @access public
 */
class CURLHandler
{

    /**
     * CURLHandler::Get()
     * 
     * Executes a standard GET request via Curl.
     * Static function, so that you can use: CurlHandler::Get('http://www.google.com');
     * 
     * @param string $url url to get
     * @return string HTML output
     */
    public static function Get($url)
    {
       return self::doRequest('GET', $url);
    }

    /**
     * CURLHandler::Post()
     * 
     * Executes a standard POST request via Curl.
     * Static function, so you can use CurlHandler::Post('http://www.google.com', array('q'=>'belfabriek'));
     * If you want to send a File via post (to e.g. PHP's $_FILES), prefix the value of an item with an @ ! 
     * @param string $url url to post data to
     * @param Array $vars Array with key=>value pairs to post.
     * @return string HTML output
     */
    public static function Post($url, $vars, $auth = false) 
    {
       return self::doRequest('POST', $url, $vars, $auth);
    }

    /**
     * CURLHandler::doRequest()
     * This is what actually does the request
     * <pre>
     * - Create Curl handle with curl_init
     * - Set options like CURLOPT_URL, CURLOPT_RETURNTRANSFER and CURLOPT_HEADER
     * - Set eventual optional options (like CURLOPT_POST and CURLOPT_POSTFIELDS)
     * - Call curl_exec on the interface
     * - Close the connection
     * - Return the result or throw an exception.
     * </pre>
     * @param mixed $method Request Method (Get/ Post)
     * @param mixed $url URI to get or post to
     * @param mixed $vars Array of variables (only mandatory in POST requests)
     * @return string HTML output
     */
    public static function doRequest($method, $url, $vars=array(), $auth = false)
    {
        $curlInterface = curl_init();

        curl_setopt_array ($curlInterface, array( 
            CURLOPT_URL => $url,
            CURLOPT_CONNECTTIMEOUT => 2,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FOLLOWLOCATION =>1,
            CURLOPT_HEADER => 0));

        if (strtoupper($method) == 'POST')
        {
            curl_setopt_array($curlInterface, array(
                CURLOPT_POST => 1,
                CURLOPT_POSTFIELDS => http_build_query($vars))
            );  
        }
        if($auth !== false)
        {
              curl_setopt($curlInterface, CURLOPT_USERPWD, $auth['username'] . ":" . $auth['password']);
        }
        $result = curl_exec ($curlInterface);
        curl_close ($curlInterface);

        if($result === NULL)
        {
            throw new Exception('Curl Request Error: '.curl_errno($curlInterface) . " - " . curl_error($curlInterface));
        }
        else
        {
            return($result);
        }
    }

}

只需将其转储到 class.CURLHandler.php 中,您就可以这样做:

当然,使用 $_REQUEST 并不是很安全(您应该检查 $_SERVER['REQUEST_METHOD']),但您明白了。

<?php
include('class.CURLHandler.php');
die CURLHandler::doRequest($_SERVER['REQUEST_METHOD'], 'http://server/myaction', $_REQUEST);
?>

当然,CURL 并未安装在所有地方,但我们有 native PHP curl emulators for that.

此外,这为您提供了比 Request.Forward 更大的灵 active ,因为您还可以捕获输出并对其进行后处理。

关于php - PHP 是否具有与 Java 的 RequestDispatcher.forward 等效的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/433774/

相关文章:

javascript - 在成功登录后运行 HTTP post

php - 如何保护 PHP 脚本?

php - 使用 "mysql_fetch_array();"制作表格无法正常工作

java - com.mysql.jdbc.MysqlDataTruncation : Data truncation: Incorrect date value

mysql - 使用jsp连接到mySQL数据源的问题

c - 如何绕过阻止直接连接的网站?

scala - 使用 Akka-Streams HTTP 将整个 HttpResponse 主体作为字符串获取

javascript - 对事件目录进行 ajax 调用并使用 post 提取缩略图照片

javascript - 处理 iOS 虚拟键盘 “previous” , “next” , “Go/Enter” 按钮

java - 在同一注册页面JSP和Servlet中加载数据列表