spring-boot - 在没有模板引擎的情况下有条件地提供静态内容 [英] spring-boot - Conditionally serve static content without template engine

查看:37
本文介绍了spring-boot - 在没有模板引擎的情况下有条件地提供静态内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态页面,我想在特定 URL 上有条件地提供该页面.
使用 spring-boot,我可以将页面放在 staticpublic 资源目录中,并将它们提供给所有人,但是如果我想通过功能标志那么这不合适.
使用模板引擎,我可以将页面作为模板加载并返回对视图的引用.但是,我的应用程序相当简单,我不想在不需要模板引擎的情况下使用模板引擎.
我希望能够使用控制器来确定页面是否被提供的天气.让控制器返回静态页面的最简单方法是什么?

I have a static page that I want to conditionally serve on a particular URL.
With spring-boot I can place pages in the static or public resource directories and have them served to everyone, but if I want to restrict access or disable access to them via a feature flag then this is not suitable.
Using a template engine I can load the page as a template and return a reference to the view. However my application is fairly simple and I don't want to utilize a template engine when I otherwise have no need for one.
I want to be able to use a controller to determine weather the page is served or not. What is the simplest way to have a controller return a static page?

推荐答案

我发现从控制器返回静态内容的最简单方法是返回一个 Resource.Resource 类有多种实现,但是 ClassPathResource 最适合 spring-boot 应用.
在常规 spring-boot 应用程序中,当 mycondition()true 时,以下示例将显示 src/main/resources/path/to/mypage.html代码>,否则返回 404.

The simplest way I have found to return static content from a controller is to return a Resource. There are multiple implementations of the Resource class but ClassPathResource makes the most sense for a spring-boot app.
In a regular spring-boot application the below example will display src/main/resources/path/to/mypage.html when mycondition() is true and return a 404 otherwise.

@RequestMapping("mypage.html")
public Resource myPage() {
    if(mycondition()) {
        return new ClassPathResource("path/to/mypage.html");
    } else {
        throw new ResourceNotFoundException();
    }
}

@ResponseStatus(HttpStatus.NOT_FOUND)
private static class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException() {}
}

这篇关于spring-boot - 在没有模板引擎的情况下有条件地提供静态内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆