Reputation:
Let's say my web application's on development stage in Eclipse, at path C:\eclipse\workspace\myapp
(Windows).
I intend to make it generate a folder at the same directory level (C:\eclipse\workspace\myappfiles
) to store uploaded files (via new File()
) in it.
However, at production stage, my web application will be at path /var/lib/tomcat7/webapps/myapp
(Linux). It should then store files in /var/lib/tomcat7/webapps/myappfiles
.
How can I detect those paths to write the folder and files?
I experimented with some java.io.File
methods, but it seemed to not have a default method that suits me for the task.
EDIT :
I need the path like that so I could map the path for direct file access via URL.
Upvotes: 1
Views: 1428
Reputation: 48057
As david99world says in his comment: This is a really bad idea. Plus, it might not even work on future versions of tomcat or on different configurations: Tomcat can be set up not to have "exploded" webapplications at all - e.g. run from zipped *.war
files. Also, tomcat might not have write permissions to its own webapps directory (a basic precaution done to harden the system).
Imagine someone is uploading a file named "explorer.jsp" with a basic file explorer implemented in a jsp: Without taking care of it, tomcat will happily interpret this as code that needs to be executed server-side.
What you want to do is:
You'll need a little bit more work this way, but the resulting installation is so much more secure out-of-the-box.
Upvotes: 1
Reputation: 12206
There are no standard ways to get the Tomcat path from Tomcat itself. You can try to find the working directory of the Tomcat user, but this may change based on where you start the server from. The safest way to do this is add the location of any files your application creates to your configuration, and then have your webapp check the config for this location.
One simple way and portable way to do this is to place the location of myappfiles
in your web.xml:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.mycompany.MyServlet</servlet-class>
<init-param>
<param-name>appfilesdir</param-name>
<param-value>/var/lib/tomcat7/webapps/myappfiles</param-value>
</init-param>
</servlet>
Then use GenericServlet.getInitParameter from within your servlet to read it and use it:
public class MyServlet extends HttpServlet
{
private String myAppFilesDir;
public void init(ServletConfig config)
throws ServletException
{
myAppFilesDir = getInitParameter("appfilesdir");
}
}
Upvotes: 1
Reputation: 2264
It should get the job done :
File currentDirectory = new File("");
String commonPath = currentDirectory.getAbsolutePath();
commonPath = commonPath.substring(path.lastIndexOf(File.separator) + 1);
File myFilesDir = new File(commonPath + "myappfiles");
myFilesDir.mkdirs();
Upvotes: -1