Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Tomcat Webapps Read File

Posted on 2010-08-25
13
963 Views
Last Modified: 2013-11-24
I have a web application using JSP that usea a JavaBean using Tomcat server.  The JavaBean must be able to read a file located in the webapps directory as readonly.  When using new File( filename), it doesn't located the file immediately in the webapps directory.  

How do I specifiy the filename so that new File will find the file in the webapps directory?  Since the Javabean isn't a JSP/servlet, it's harder to do that.
0
Comment
Question by:lcor
  • 5
  • 3
  • 3
  • +1
13 Comments
 
LVL 10

Expert Comment

by:Hegemon
ID: 33523038
How is the web application deployed and what is its directory structure ?
0
 
LVL 27

Expert Comment

by:rrz
ID: 33523304
In your web app's web.xml file  you could have something like  

    <servlet>      
                   <servlet-name>AppContext</servlet-name>
                   <servlet-class>rrz.AppContextServlet</servlet-class>
                   <load-on-startup/>
    </servlet>  

and the servlet could  be something like  

package rrz;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AppContextServlet extends HttpServlet {
    public void init(ServletConfig config){
                   try{
                       super.init(config);
                       AppContextHolder.set(config.getServletContext());
                       System.out.println("init of AppContextServlet"); //for testing
                      }catch(ServletException se){System.out.println("error in AppContextSrevlet init");}
    }
}

and the class could be something  like  

package rrz;
import javax.servlet.ServletContext;
public class AppContextHolder{
   private static ServletContext currentContext;
   private static String dirPath;
   public static void set(ServletContext context) {
                                                   currentContext = context;
                                                   String appPath = context.getRealPath("/");
                                                   int index = appPath.indexOf("webapps");
                                                   dirPath = appPath.substring(0,index + 7);
   }
   public static ServletContext getContext(){
                                             return currentContext;
   }
   public static String getDirPath(){
                                             return dirPath;
   }
}

and in your bean you could use  
String dirPath = AppContextHolder.getDirPath();
File f = new File(dirPath);
0
 

Author Comment

by:lcor
ID: 33525858
It's a typical Tomcat deployment

webapps/mywebapp/File.txt
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 27

Expert Comment

by:rrz
ID: 33526105
Sorry I am guess I mis-understood
>The JavaBean must be able to read a file located in the webapps directory as readonly  
but if the file is inside your web app's root directory,
>webapps/mywebapp/File.txt  
then  
In your web app's web.xml file  you could have something like  

    <servlet>      
                   <servlet-name>AppContext</servlet-name>
                   <servlet-class>rrz.AppContextServlet</servlet-class>
                   <load-on-startup/>
    </servlet>  

and the servlet could  be something like  

package rrz;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AppContextServlet extends HttpServlet {
    public void init(ServletConfig config){
                   try{
                       super.init(config);
                       AppContextHolder.set(config.getServletContext());
                       System.out.println("init of AppContextServlet"); //for testing
                      }catch(ServletException se){System.out.println("error in AppContextSrevlet init");}
    }
}

and the class could be something  like  

package rrz;
import javax.servlet.ServletContext;
public class AppContextHolder{
   private static ServletContext currentContext;
   public static void set(ServletContext context) {
                                                   currentContext = context;
   }
   public static ServletContext getContext(){
                                             return currentContext;
   }
}

and in your bean you could use  
String context = AppContextHolder.getContext();
String filePath = context.getRealPath("/File.txt);
File f = new File(filePath);
0
 
LVL 27

Expert Comment

by:rrz
ID: 33526148
If you are new to java, then I should give more details.
Change my package name (rrz) to the package that contains your bean.
Please ask if you need more help.
0
 
LVL 27

Accepted Solution

by:
rrz earned 225 total points
ID: 33526182
>String filePath = context.getRealPath("/File.txt);  
error
String filePath = context.getRealPath("/File.txt");
0
 
LVL 92

Assisted Solution

by:objects
objects earned 225 total points
ID: 33526998
0
 
LVL 27

Expert Comment

by:rrz
ID: 33527211
He wants to access from his bean.
0
 
LVL 10

Assisted Solution

by:Hegemon
Hegemon earned 50 total points
ID: 33529358
I think anything related to request URL or servlet context (e.g. getRealPath()) is not related to the problem. The author needs to read a file stored INSIDE his web application, which can be deployed as an exploded application or .WAR archive and their locations can vary.

I think the only good way to access the file in this condition is like below:

ClassLoader cl = Thread.currentThread().getContextClassLoader();
BufferedReader br - new BufferedReader (new InputStreamReader(cl.getResourceAsStream("WEB-INF/somefile.xml")));

I'd like to reiterate, only if the file is included into the web app's structure. If it is external to it, use File as you would normally do.

Another not so good way would be fiddling with Tomcat properties and Tomcat API calls trying to find out how and where the application is deployed (an unpacked into a temporary dir it it was deployed as a WAR) and deriving an absolute path to the file.
0
 
LVL 92

Expert Comment

by:objects
ID: 33529376
> The author needs to read a file stored INSIDE his web application,

thats what getRealPath() is for.
0
 
LVL 10

Expert Comment

by:Hegemon
ID: 33529388
getRealPath() - .. This method returns null  if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).
0
 
LVL 92

Expert Comment

by:objects
ID: 33529421
yes, in a war won't work. afaik it cannot be achieved with a war
0
 

Author Closing Comment

by:lcor
ID: 33535310
just used realpath and passed the path to the bean.

Classloader solution was informative but not the solution I used.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
fibonacci ten numbers 4 45
hibernate insert example 13 34
Eclipse Java import and method not resolved 4 46
Setup GlassFish 4 21
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question