I have a very simple java web-application which is deployed to Tomcat.
In this application I have some code which goes like this:
package com.mywebapp.hello;
import javax.servlet.http.*;
import java.io.*;
public class PdfTwoServlet extends HttpServlet {
public void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
httpServletResponse.setContentType("application/pdf");
InputStream is = PdfTwoServlet.class.getResourceAsStream("/two.pdf");
When I compile my code and deploy it to tomcat, the directory structure goes like this:
This is under say C:\Tomcat\webapps\myApplication :
So
PdfTwoServlet.class.getResourceAsStream("/two.pdf");
works fine and finds the file two.pdf which is under classes folder, but I have no idea how this works.
Accessing properties file in a JSF application programmatically here BalusC says:
The Class#getResourceAsStream() can take a path which is relative to the location of the Class which you're using there as starting point. If you use /foo/filename.properties, then it will actually load foo/filename.properties from the classpath root.
I have 2 questions:
1) Why is the classpath root is WEB-INF\classes folder? Where is it determined? ( As far as I understand, it should be because code is working fine as I said. )
According to this: http://docs.oracle.com/javase/tutorial/essential/environment/paths.html , I do not have a classpath set in my local machine. So maybe when I start tomcat, it sets the classpath? But there are few web-apps deployed, are there few classpaths?
2) Is there a better way to make this work instead of: PdfTwoServlet.class.getResourceAsStream ? Something like getClassPath().getResourceAsStrem ?
Edit: Maybe someone more experienced and with better English can edit the title of this question. I am not sure if it is good enough.