【问题标题】:Redirect a page to another url, but keeping the view name in the address bar将页面重定向到另一个 url,但在地址栏中保留视图名称
【发布时间】:2013-09-03 16:32:57
【问题描述】:

我想保留网址“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”?

【问题讨论】:

    标签: java html spring spring-mvc


    【解决方案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>
    

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

    【讨论】:

      【解决方案2】:

      您将无法通过视图转发来做到这一点。您必须使用 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;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-03-17
        • 2017-04-07
        • 2012-05-22
        • 1970-01-01
        • 2012-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-09
        相关资源
        最近更新 更多