0

I have Classes that Generates jasper-reports i am using

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).

Now on my server i have the jaspers in [tomcat]/webapp/[myapp]/reports/jasper

How can i access these files from the Jar?

M.Hussaini
  • 135
  • 1
  • 5
  • 15
  • I think the reponse is in this post http://stackoverflow.com/questions/861500/url-to-load-resources-from-the-classpath-in-java – srgt1981 Jul 13 '12 at 11:50
  • I think the response is in the post 'http://stackoverflow.com/questions/861500/url-to-load-resources-from-the-classpath-in-java' – srgt1981 Jul 13 '12 at 11:52

2 Answers2

0

You access a resource in web application using

ServletContext.getResourceAsStream(RESOURCE_HOME + "/srPaySlipSalaryComp.jasper");

The codes above will look from the following locations:

  • web application folder
  • in /META-INF/resources of each library present in WEB-INF/lib

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
  • in any library in WEB-INF/lib
Ramesh PVK
  • 15,200
  • 2
  • 46
  • 50
  • OK. Can i call servlet context from within a class in Jar? Because i am not using servlet? Just JSP calling the Class in my Jar. – M.Hussaini Jul 13 '12 at 10:55
  • Lets JSP pass the servlet context to that class. – Ramesh PVK Jul 13 '12 at 10:56
  • 1
    No, it won't. getClass().getResourceAsStream() only looks in the classpath. It doesn't know about the webapp. And ServletContext loads from the webapp's root and from META-INF/resources, but not from the classpath. – JB Nizet Jul 13 '12 at 10:56
0

getClass().getResource() loads a resource using the class loader. 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.

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.

If you really want to put the jasper files in the webapp, then you need to load the resource using 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. So you shouldn't call getFile(). Pass the URL, or the InputStream returned by getResourceAsStream(), to the Jasper API.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255