October 2007
Intermediate to advanced
496 pages
16h 50m
English
Many web applications make use of the filesystem to save and load data. If you run
Tomcat with the SecurityManager enabled, it will not
allow your web applications to read and write their own data files. To make these web
applications work under the SecurityManager, you must
grant your web application the proper permissions.
Example 6-1 shows a simple HttpServlet that attempts to create a text file on the filesystem and displays
a message indicating if the write was successful.
Example 6-1. Writing a file with a servlet
package com.oreilly.tomcat.servlets; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.GenericServlet; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * This servlet attempts to write a file into the webapp's document * root directory. */ public class WriteFileServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException { // Try to open a file and write to it. String catalinaHome = "/opt/tomcat"; File testFile = new File(catalinaHome + "/webapps/ROOT", "test.txt"); FileOutputStream fileOutputStream = new FileOutputStream(testFile); fileOutputStream.write(new String("testing...\n").getBytes( )); fileOutputStream.close( ); // If we get down this far, the file was created successfully. PrintWriter out = response.getWriter( ...Read now
Unlock full access