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