【问题标题】:Play.current is deprecated - Load files in a class used by a Controller (Java Play Framework 2.7)?Play.current 已弃用 - 在控制器使用的类中加载文件(Java Play Framework 2.7)?
【发布时间】:2019-11-28 17:12:37
【问题描述】:

在 Play Framework(版本 /public/images 加载图像文件:

Option<URL> url = Play.current().resource("/public/images/myimage.png");
URL imageurl = url.get();

这适用于DEV-模式和后来的PROD-模式。

Play.current().resource 的正确替换是什么以获得正确的文件路径?或者加载文件的最佳方式是什么?

因为带有MyClass.getClass().getResource("/public/images/myimage.png") 或仅MyClass.getClass().getResource("myimage.png") 的普通Java 方法(当文件与MyClass.java 位于同一文件夹中时)在PROD 中不起作用>-模式。

感谢您的帮助!

顺便说一句:其他类似的问题(Play.current is deprecated in play 2.5 for eaxmple)没有帮助,因为我不想加载配置文件。

【问题讨论】:

    标签: java playframework


    【解决方案1】:

    我猜你需要注入 Environment 来获取资源路径。可以通过调用resource方法来完成。

    environment.resource("/public/images/myimage.png")
    

    【讨论】:

    • 我已经试过了。也许我用错了。但是下面的代码在 MyController.java 中总是会返回 null: private Environment environment = null; @Inject public MyController(Environment environment) { this.environment = environment; } @BodyParser.Of(BodyParser.Json.class) public Result mymethod(Http.Request request) { URL imageUrl = environment.resource("/public/images/myimage.png"); // imageUrl 始终为空! }
    • 它应该可以工作。您是否在此处提到的路由中配置了资产控制器 - playframework.com/documentation/2.7.x/…?您也可以尝试拨打environment.classLoader()并通过它请求文件URL
    • 你能否检查一下public 文件夹是否存在于dist 中?
    • 我们删除了路由文件中的 GET /assets/*file controllers.Assets.at(file) 行,因为它也被弃用了......现在它正在工作。非常感谢。
    猜你喜欢
    • 2016-08-18
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    相关资源
    最近更新 更多