简体   繁体   中英

Redirect a page to another url, but keeping the view name in the address bar

I would like to keep the url " http://www.mywebsite.com/hello/1111 " but I want to show another external page, lets say that I want to show google.com.

Here is the code of my controller:

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

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

}

How can I keep " http://www.mywebsite.com/hello/1111 " in the address bar, and show "www.google.com"?

One way to do this would be to use an iframe in the view you are generating for the user.

@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";
}

Then in the hello.jsp file could look like:

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

Another way would be to make a request to the external website and stream the response to the user.

You won't be able to do it with view forwarding. You have to use an HTTP client to get the response from the target url and write that content to response body of the current request.

@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);
}

or with @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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM