【问题标题】:Overriding static file routes in Spark depending on the Accept header根据 Accept 标头覆盖 Spark 中的静态文件路由
【发布时间】:2017-08-30 06:05:10
【问题描述】:

我正在使用 Spark 的 (http://sparkjava.com/) 静态文件路由,通过以下方式设置:

externalStaticFileLocation('.../public');

用于提供放置在 public 目录中的 index.html 页面等。如此有效,当您点击服务器的 URL 时,您将返回您的 index.html。到目前为止一切顺利...

但是,当请求包含特定的 Accept 标头时,我想覆盖此行为,例如 application/rdf+xml(与默认的 text/html 基本不同>)。在这种情况下,我想返回一些特定数据而不是 index.html 页面。

在 Spark 中是否有一种简单的方法来实现这一点?我在文档中找不到任何解决方案...感谢您的任何提示!

【问题讨论】:

    标签: java routing spark-java


    【解决方案1】:

    由于您想要做出的行为改变,您现在想要提供的内容不再是静态的,而是动态的

    您需要从静态内容目录中删除 index.html 并将其移动到资源目录(通常为 src/main/resources/templates)。

    然后,您需要为您的域名根 (/) 创建一个路由,并使用 template engine 提供内容。

    使用模板引擎时,您通常会将动态数据注入静态模板。通常,您使用某种地图来执行此操作。 在text/html 的情况下,您的地图将为空,然后就像以前一样 - 提供静态页面。如果是application/rdf+xml,您将使用相关数据填充地图,然后提供生成的动态页面。

    例子:

    get("/", (request, response) -> {
        if (isTextHtml(request)) {
            // serve the index.html template as is (empty map, not null though)
            // In this case index.html functinos as a static page
        } else {
            // use a map to have all relevant data for the index.html template
            // In this case index.html functinos as a "real" template
        }
    });
    

    【讨论】:

    • 是的,这很好用@SHG,谢谢!您是否有任何想法如何强制执行自定义的绝对目录路径来存储模板..?
    • @szymon 我没有,抱歉。但是为什么不遵循 Web 项目的常规约定呢?
    • 公平点 - 我需要重新考虑我真正想要以这种方式实现的目标和原因......
    猜你喜欢
    • 2015-05-01
    • 1970-01-01
    • 2020-03-06
    • 2017-04-04
    • 1970-01-01
    • 2020-07-11
    • 2013-02-10
    • 2022-01-04
    • 2023-03-23
    相关资源
    最近更新 更多