Do you want to create a servlet that backs up published data to a file based on a file name guid

advertisements

So I pushed my java app to a server, pretty excited about that.

Now I want to test something, how can I save the posted data to my servlet to a file, and the filename should be a unique guid.

I have this so far:

public class TestServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
            throws javax.servlet.ServletException, IOException {

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
            throws javax.servlet.ServletException, IOException {

        PrintWriter printWriter = response.getWriter();

        printWriter.print("hello, world from testservlet!");

    }
}

So assuming the http posted data (say around 50K) will be posted to the field 'payload', how can I grab the posted text, and save it to a file, with the filename being a GUID.

Does java have a construct to clean up an open file, like in c#:

using(var file = new ....)
{
  // write to file
}

That closes the connection and cleans up memory etc.

Also, do I need to set special permissions for tomcat to save this file?

I just set things up by default right now (just playing around on a VPS) using ubuntu 11, installed tomcat6.

Thanks.


You can user request to read the "payload", see the API doc for ServletRequest:

request.getParameter("payload");

You can use File to create the file, see AP doc:

File newFile = new File("fileName");
boolean isCreated = newfile.createNewFile();

You can write to the file as follows,

BufferedWriter out = new BufferedWriter(new FileWriter(newFile));
out.write(payLoad);
out.close();

For GUID you see this Create a GUID in Java

And for the clean up, you don't have to worry about it in Java, it's Garbage Collector ( What is the garbage collector in Java? ) does it for you automatically when the reference goes out of scope.

But you should close the resources like out.close to release it back to the system when you are done with it.

Also, do I need to set special permissions for tomcat to save this file?

You do not need to do that because tomcat is just a server, it's more related to the file system (OS). I use Glassfish on Unix and I don't need to do anything like that to create file.