Java/Tomcat: ServletContext & getResourceAsStream Problems

北城以北 提交于 2019-12-25 05:23:09

问题


I am trying to access a conf file (located in the WEB-INF folder) from a Tomcat web app. At the moment, I have the location of the file hard coded as a String. However, this does not work when the tomcat/webapps folder is in a different location than my hard coded String indicates. I've looked online and it seems like using the getResourceAsStream () method is what I'm looking for, but I'm having a hard time getting it to work. My application is not liking it when I call the getServletContext () method. Can anyone help me?

EDIT: The relevant block of code

BufferedReader myReader = new BufferedReader (new InputStreamReader (getServletContext ().getResourceAsStream ("/WEB-INF/conf.txt")));

回答1:


To solve this problem I created two folders under WEB-INF (path/to/app/WEB-INF/classes/mypackage/) and then put my files in this folder. Then, from my POJO I called this.getClass.getResourceAsStream ("<filename>") to open up a stream. To just get a String that was the complete absolute path name of a file I did this.getClass.getResource ("<filename>").toString ().substring (5).




回答2:


If you are trying to load a file from the WEB-INF directory in Tomcat, use the following code:

For example, for a file in WEB-INF/config/config.xml

ServletContext context = ....//get servlet context
InputStream is = context.getResourceAsStream("/WEB-INF/config/config.xml");



回答3:


If your config file is at /WEB-INF/config.xml, you could access it from a servlet by using "../config.xml" instead of a full path. This works because compiled application classes are normally located within /WEB-INF/classes.




回答4:


Following code worked for me. I kept my config file under WEB-INF/

web.xml code snippet:

<servlet>
    <servlet-name>wizardcontroller</servlet-name>
    <servlet-class>com.sg.poc.wizard.controller.CustomerWizardController</servlet-class>
    <init-param>
        <param-name>plm-config</param-name>
        <param-value>plm-config.xml</param-value>
    </init-param>
</servlet>

Servlet code snippet:

String configfile = config.getInitParameter("plm-config") ;
InputStream is = config.getServletContext().getResourceAsStream("/WEB-INF/"+configfile);
System.out.println("Resource Stream is : "+is);


来源:https://stackoverflow.com/questions/12081578/java-tomcat-servletcontext-getresourceasstream-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!