如何在Tomcat中部署的未爆炸战争文件中读取资源文件? [英] How can I read a resource file in an unexploded war file deployed in Tomcat?

查看:76
本文介绍了如何在Tomcat中部署的未爆炸战争文件中读取资源文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试加载二进制映像文件以在服务器端Java代码中进行一些处理.我目前将图像放置在执行类所在的包中,并调用:

I am trying to load a binary image file to do some processing inside my server-side Java code. I am currently placing my image in the package where my executing class exists and calling:

Image img = Image.getInstance(this.getClass().getResource("logo.png"));

当我在爆炸式战争设置中的开发箱上运行Tomcat时,此方法工作正常,但是当我部署到运行Tomcat且不会爆炸war文件的服务器时,对getResource的调用将返回null.

This works fine when I'm running Tomcat on my development box in an exploded war setup, but when I deploy to a server running Tomcat where it doesn't explode war files, the call to getResource returns null.

我还尝试过将图像移动到上下文根目录并像这样访问它:

I've also tried moving the image to my context root and accessing it like this:

Image img = Image.getInstance(this.getClass().getResource("/../../logo.png"));

同样,这可以在我的开发箱中使用,但是当我将其部署到其他地方时则无效.

Again, this works on my development box, but not when I deploy it elsewhere.

是否有更好的方法来访问此文件?我在做什么错了?

Is there a better way to access this file? What am I doing wrong?

谢谢!

推荐答案

如果使用Maven进行构建,则需要确保将图像实际放置到存档中.

If you are building using Maven, you'll want to make sure the image actually gets placed into the archive.

将资源放入您的src/main/resources目录.然后使用以下命令访问它们:

Put resources in your src/main/resources directory. Then access them with:

this.getClass().getResource("/logo.png"); 

或:

Thread.currentThread().getContextClassLoader().getResource("logo.png"); 

(以上注释中的代码示例,但请在答案中显示得更明显)

(Code samples from comment above, but put in the answer to be more visible)

这篇关于如何在Tomcat中部署的未爆炸战争文件中读取资源文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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