Spring URL 到 .HTML 的 MVC 1 对 1 映射,不公开路径

Spring MVC 1 to 1 mapping of a URL to .HTML without exposing path

我在不提供任何 JSP 服务的 Web 服务上使用 Spring 4.1.5 和 Boot 1.2。我不想添加 JSP servlet,但我希望它提供一个金丝雀页面,以更漂亮的 html 类型格式显示将在 /manage/health 中提供的信息端点。

我在 webapp/canary/canary.html 中有一个文件,我想从 url 提供这个文件:www.mywebservice.com:9343/canary,就像那样,而不是 canary.html

我试过这样做:

@Configuration
public class CanaryConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/canary")
                .addResourceLocations("/canary/canary.html");
    }
}

但这不起作用。

期待处理程序提供文件名。所以换句话说,位置应该是这样的:/canary/

处理程序会是这样的:/canary/**

这样一来,URL www.mywebservice.com:9343/canary/canary.html 就可以发挥作用了。

但是,我希望 URL 无需输入 html 即可将 www.mywebservice.com:9343/canary 解析为 webapp/canary/canary.html

这在 jsp servlet 中非常容易,因为您可以设置后缀等...

我查看了 ResourceResolver,但我不明白如何将其 link 放入我当前的配置中。

看起来像我想要的:

Provides mechanisms for resolving an incoming request to an actual Resource and for obtaining the public URL path that clients should use when requesting the resource.

参见:ResourceResolver Documentation

任何帮助都会非常有益。

还有我很清楚我可以把html放在resources/static和其他几个自动配置的地方。这总是需要输入 .html ,这不是我在这种情况下想要的,所以不会起作用。谢谢!

您可以使用视图控制器来完成。这是它的一个示例。希望这有帮助。

    public class AppConfig extends WebMvcConfigurerAdapter {

        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/canary").setViewName("/canary/canary.html");
        }
}

注意:如果您使用 tomcat,您可能需要配置 jsp servlet 到服务器 html 文件。

Related post here

供参考,所选答案与以下相同:

@Controller
public class CanaryController {

    @RequestMapping(value="/canary", method=RequestMethod.GET)
    public String getCanary() {
        return "/canary/canary.html";
    }
}

只要 canary(或任何 file/folder)在您的 webapp 文件夹中,上面的代码就可以工作。

当我尝试这个时,我试图在我的 YAML (.yml) 文件中将后缀设置为 .html 但它不起作用我认为它需要 return 到如果它不是 RestController,则为 servlet。我错了。