在给定相对 URI 的情况下测试资源是否存在
我编写了一个小型 Java servlet,它可以根据给定的参数(包括标签、高度、宽度等)动态生成图像按钮,并将每个新按钮添加到缓存中。它工作得很好,但每次调用都需要一个 servlet 调用来显示按钮或其突出显示的版本。我转储了缓存并制作了应用程序中当前使用的所有按钮的 PNG 文件,将这些文件添加到应用程序中,以便可以通过“/images/button/xyz.png”引用它们,其中文件名是哈希值输入参数。
这工作得很好,但我希望在有人添加新按钮时调用我原来的 servlet。我使用自定义标签来定义这些按钮,因此在 JSP 编译时会调用标签处理程序...所以我可以选择使用预生成的按钮之一,或者生成对 servlet 的引用,这样它可以在显示按钮时呈现该按钮。
我的问题是:如何检测图像是否可用于预渲染?我不确定基于完整路径创建 URL 对象然后调用 getResource() 的调用是否是答案——我不希望它此时加载图像,我只需要知道它是否存在。
有没有某种方法可以创建一个 File 对象,该对象将采用相对 URI 并允许我测试是否存在?
I wrote a little Java servlet that would dynamically generate an image button given parameters including label, height, width and so on, and it would add each new one to a cache. It worked fine, BUT it required a servlet call for every call to display the button or its highlighted version. I dumped the cache and made PNG files of all the buttons used at the moment in the app, added those files to the app so they could be referenced by "/images/button/xyz.png", where the filename is a hash of the input parameters.
That works fine, but I want my original servlet to be called on the occasion when someone has added a new button. I use a custom tag to define these buttons, so the tag handler gets called when the JSP compiles... so I have a point where I can choose to use one of the pre-generated buttons, OR generate a reference to the servlet so it can render the button when it is displayed.
My question is: How can I detect the image is available in pre-rendered for? I'm not sure that a call to create a URL object based off the full path and then doing a call to getResource() is the answer -- I don't want it to load the image at this time, I just need to know if it exists.
Is there some way to create a File object that would take a relative URI and allow me to test for existence?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想您正在谈论
java.lang.Class
上的getResource()
方法。这实际上非常适合该问题,因为 根据约定,如果给定路径不存在资源,它将返回null
。在您使用 getResourceAsStream()(或类似方法)之前,资源实际上并未加载,因此这不是性能问题。I suppose you are talking about the
getResource()
method onjava.lang.Class
. This is actually well-suited to the problem since by contract, it will returnnull
if no resource exists with the given path. The resource isn't actually loaded until you usegetResourceAsStream()
(or similar) so this is not a performance concern.您可以在实用程序类中尝试以下方法。
这假设您的图像文件名是唯一的。
You can try the following approach in a utility class.
This assumes your image file names are unique.