[英]Access Files in tomcat web-app from a Class in Jar inside WEB-INF/lib
I have Classes that Generates jasper-reports i am using 我有会生成我正在使用的jasper报告的类
private String RESOURCE_HOME = "/reports/jasper";
getClass().getResource(RESOURCE_HOME + "/srPaySlipSalaryComp.jasper").getFile();
I package this class in a jar and put into my application on tomcat @(WEB-INF/lib). 我将此类包装在一个罐子中,然后放入tomcat @(WEB-INF / lib)上的应用程序中。
Now on my server i have the jaspers in [tomcat]/webapp/[myapp]/reports/jasper 现在在我的服务器上,我在[tomcat] / webapp / [myapp] / reports / jasper中遇到了碧玉
How can i access these files from the Jar? 如何从Jar中访问这些文件?
You access a resource in web application using 您使用来访问Web应用程序中的资源
ServletContext.getResourceAsStream(RESOURCE_HOME + "/srPaySlipSalaryComp.jasper");
The codes above will look from the following locations: 上面的代码将从以下位置查找:
/META-INF/resources
of each library present in WEB-INF/lib
/META-INF/resources
WEB-INF/lib
存在的每个库的/META-INF/resources
中 If you want to use the code you have 如果您想使用代码
private String RESOURCE_HOME = "/reports/jasper";
getClass().getResource(RESOURCE_HOME + "/srPaySlipSalaryComp.jasper").getFile();
the file should be present in the following two locations: 该文件应位于以下两个位置:
WEB-INF/classes
WEB-INF/lib
WEB-INF/lib
中的任何库中 getClass().getResource()
loads a resource using the class loader. getClass().getResource()
使用类加载器加载资源。 So the resources it can load are resources that are accessible in the classpath. 因此,它可以加载的资源是可在类路径中访问的资源。 So it can only load from a jar in
WEB-INF/lib
, or from WEB-INF/classes
, or a jar in tomcat's classpath. 因此,只能从
WEB-INF/lib
的jar或WEB-INF/classes
或tomcat的classpath中的jar加载。
One solution (probably the best one) is thus to also put the jasper files in a jar file in WEB-INF/lib
, or in a directory under WEB-INF/classes
. 因此,一种解决方案(可能是最好的解决方案)是将jasper文件放在
WEB-INF/lib
中的jar文件中,或WEB-INF/classes
下的目录中。
If you really want to put the jasper files in the webapp, then you need to load the resource using ServletContext.getResource() . 如果您确实要将jasper文件放入webapp,则需要使用ServletContext.getResource()加载资源。
In both solutions, what you'll get is not an URL pointing to a file, but an URL to a resource inside a jar or a war. 在这两种解决方案中,您将获得的不是指向文件的URL,而是指向jar或war中的资源的URL。 So you shouldn't call
getFile()
. 因此,您不应调用
getFile()
。 Pass the URL, or the InputStream returned by getResourceAsStream()
, to the Jasper API. 将URL或
getResourceAsStream()
返回的InputStream传递给Jasper API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.