O'Reilly logo

Tomcat: The Definitive Guide, 2nd Edition by Ian F. Darwin, Jason Brittain

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Granting File Permissions

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required