如何在运行时在WAR中找到非Java资源? [英] How can I locate a non-Java resource in a WAR at runtime?

查看:117
本文介绍了如何在运行时在WAR中找到非Java资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在运行时从我在Tomcat上运行的WAR运行一个shell脚本。

I need to run a shell script at runtime from a WAR that I run on Tomcat.

因此,我把我的脚本theScript.sh放在我的src中/ main / resources目录(因为,是的,我使用Maven)。这个目录在classpath中,我已经检查过了。

Thus, I've placed my script theScript.sh in my src/main/resources directory (because, yes, I use Maven). This directory is in the classpath, I've checked it.

在代码中,我想将我的脚本复制到临时目录中。所以我试图通过我的ClassLoader得到它:

In the code, I want to copy my script in a temp directory. So I've tried to get it via my ClassLoader:

URL myURL = ClassLoader.getSystemResource("theScript.sh");
if (myURL == null) {
    LOG.error("Couldn't find the resource");
}

猜猜怎么着?是的,无法找到资源一直出现在我的日志中。

And guess what? Yes, the "Couldn't find the resource" keeps appearing all over the place in my logs.

我知道我在这里做错了吗?

Any idea what I'm doing wrong here?

我的环境是传统的Eclipse / Tomcat。

My environment is the traditional Eclipse/Tomcat thing.

推荐答案

你没有想要使用System cloassloader - 通常只能找到属于Tomcat或JRE的资源。

You don't want to use the System cloassloader - that would typically only find resources that are part of Tomcat or the JRE.

您想要从用于的类加载器加载资源加载您的WAR文件。
有几种方法可以做到这一点,但官方方式是访问 ServletContext javadoc )并调用 getResource getClassLoader()。getResource 就此。

You want to load the resource from the classloader that was used to load your WAR file. There's a couple of ways to do that, but the official way would be to get access to the ServletContext (javadoc) and call either getResource or getClassLoader().getResource on that.

如果您没有 ServletContext 可用,然后你可以使用类加载器为你知道来自WAR文件的类作弊。类似

If you don't have the ServletContext available, then you can "cheat" by using the classloader for a class that you know came from your WAR file. Something like

this.getClass().getClassLoader().getResource("xyz");

其中是您已部署的类在你的WAR文件中。

where this is your class that's been deployed inside your WAR file.

这篇关于如何在运行时在WAR中找到非Java资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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