将页面重定向到另一个URL,但将视图名称保留在地址栏中

时间:2013-09-03 16:32:57

标签: java html spring spring-mvc

我想保留网址“http://www.mywebsite.com/hello/1111”,但我想展示另一个外部网页,让我说要显示google.com。

这是我的控制器的代码:

@RequestMapping(value = {"hello/{id}"}, method = RequestMethod.GET)
public String helloGet(Model model, @PathVariable Integer id) {

    final String url = "http://www.google.com"
    return url;

}

如何在地址栏中保留“http://www.mywebsite.com/hello/1111”,并显示“www.google.com”?

2 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是在为用户生成的视图中使用iframe

@RequestMapping(value = {"hello/{id}"}, method = RequestMethod.GET)
public String helloGet(Model model, @PathVariable Integer id) {

    final String url = "http://www.google.com"
    model.addAttribute("externalUrl", url);

    return "hello";
}

然后在hello.jsp文件中看起来像:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <iframe src="${externalUrl}"></iframe>
    </body>
</html>

另一种方法是向外部网站发出请求并将响应流式传输给用户。

答案 1 :(得分:1)

您无法通过视图转发执行此操作。您必须使用HTTP客户端从目标URL获取响应,并将该内容写入当前请求的响应主体。

@RequestMapping(value = {"hello/{id}"}, method = RequestMethod.GET)
public void helloGet(Model model, @PathVariable Integer id, HttpServletResponse response) {

    final String url = "http://www.google.com"
    // use url to get response with an HTTP client
    String responseBody = ... // get url response body 
    response.getWriter().write(responseBody);
}

@ResponseBody

@RequestMapping(value = {"hello/{id}"}, method = RequestMethod.GET)
public @ResponseBody String helloGet(Model model, @PathVariable Integer id) {

    final String url = "http://www.google.com"
    // use url to get response with an HTTP client
    String responseBody = ... // get url response body 
    return responseBody;
}