2

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 :

enter image description here

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.

4

1 回答 1

2

对于 1) servlet 应用程序中的类路径根是按规范指定 jar 的 WEB-INF\classes 文件夹,加上该 WAR 的 WEB-INF/lib 中所有 jar 的根。这些位置中的任何内容都将被视为类路径的根。

关于 tomcat 中的类路径如何工作的问题,当 tomcat 部署时,它按以下方式设置类路径:每个 WAR 对应一个单独的类加载器,该类加载器可以访问 WEB-INF/classes 和 WEB-INF/lib 中的所有 jar。

默认如果这里没有找到搜索到的资源,会在tomcat/lib目录下搜索。如果那里没有找到,它会询问父类加载器,等等,解释可以在这里找到

如果部署了多个 web 应用程序,每个 WAR 将有它自己的类加载器,指向它自己的 WEB-INF/classes 和 WEB-INF/lib jars。

对于 2) 没有像 getClasspath() 这样的方法,ServletContext.getResourceAsStream() 是 servlet 应用程序从 WAR 内部获取资源的建议方法。WAR 可能会被压缩或爆炸,这对两者都适用,请参阅此答案

于 2013-10-22T21:24:05.503 回答