在Spring中返回一个没有重定向的静态html

时间:2014-06-05 22:26:45

标签: java spring-mvc

所以我想在不发送重定向的情况下返回HTML页面。原因是使用重定向更改了浏览器中的URL,如果他们没有登录,我无法将某人重定向到登录。有什么最直接的方法呢?看起来它应该很简单,不使用jsp或其他服务器端视图技术。

2 个答案:

答案 0 :(得分:14)

您可以使用forward

示例:

/static/myWebpage.html是你的静态html页面

此代码将返回myWebpage.html的内容而不更改网址

@Controller
@RequestMapping("/path")
public class TestingController {
    @RequestMapping("/page")
    public String someOtherPage(HttpServletRequest request, HttpServletResponse response) {
        return "forward:/static/myWebpage.html";
    }
}

您的网址将是" localhost / path / page"但您将查看" localhost / static / myWebPage.html"

答案 1 :(得分:0)

给出的答案above对于大多数Spring配置是正确的。其他时候,您只会得到一个Content-Type: text/plain网页,其中包含转发信息作为文本。您必须将转发信息明确传递给ModelAndView

@Controller
@RequestMapping("/path")
public class TestingController {
    @RequestMapping("/page")
    public ModelAndView someOtherPage(HttpServletRequest request, HttpServletResponse response) {
        return new ModelAndView("forward:/static/myWebpage.html");
    }
}