Java Tutorials
Building Hadoop MapReduce Jobs In Java
Building XML With Java And DOM
Creating Java Servlets With NetBeans
Basic File Manipulation With Java
Introduction To Java

Creating Java Servlets With NetBeans

Unsubscribe Servlet

Time to create a second servlet. Just as before right click on the project and select new then servlet. Name the servlet Unsubscribe. This servlet is going to focus on reading and writing files. For detailed information about see the Java File Access Tutorial. This servlet will use the FileInputStream to read the file and RandomFileAccess to write the file.

The HTML for the form. The submission is handled via AJAX covered here.

 <div id="divUnsubscribeForm">
     <form name="unsubscribeForm">
         EMail Address: <input type="text" id="unsubemail" 
           name="unsubemail"/><br/>
         <input type="button" name="submit" value="Unubscribe" 
           onclick="ajaxUnsubscribeFormSubmit()"/><br/>
     </form>
 </div>
 <div id="divUnsubscribeResponse">
     Click to unsubscribe
 </div>

For brevity get the complete ajax.js from the Javascript Introduction to AJAX Tutorial and paste it into the ajax.js file. Add another 'import java.io.*;' line with the initial imports at the top. The function processRequest should be changed to contain the following code:

        boolean found = false;
        boolean error = false;
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String memList = null;
            File readFile = new File("/tmp/membership_list.txt");
            FileInputStream in = new FileInputStream(readFile);
            byte bt[] = new byte[(int)readFile.length()];
            in.read(bt);
            memList = new String(bt);
            in.close();
            String[] line = new String[2];
            String[] memListArray = new String[memList.split("n").length];
            String[] newListArray = new String[memList.split("n").length];
            int j = 0;
            memListArray = memList.split("n");
            for (int i=0; i < memListArray.length; i++) {
                line = memListArray[i].split("t");
                if(!line[0].equalsIgnoreCase(request.getParameter("unsubemail"))) {
                    newListArray[j] = memListArray[i];
                    j++;
                } else {
                    found = true;
                }
            }
            //Rewrite the file without the unsubscribed email
            if (found) {
                byte[] b;
                String str = "";
                if (newListArray.length > 0) {
                    for (String s : newListArray) {
                        str = str + s + "n";
                    }
                    b = str.getBytes();
                } else {
                    b = new String("").getBytes();
                }
                File outputFile = new File("/tmp/membership_list.txt");
                File oldFile = new File("/tmp/membership_list.old");
                outputFile.renameTo(oldFile);
                RandomAccessFile fileOut = new RandomAccessFile("/tmp/membership_list.txt", "rw");
                fileOut.write(b);
                fileOut.close();
            }
        } catch (Exception ex) {
            error = true;
        } finally {
            //Build the response
            if (error) {
                out.println("<root>");
                out.println("    <result>Error</result>");
                out.println("</root>");    
            } else if (found) {
                out.println("<root>");
                out.println("    <result>Success</result>");
                out.println("</root>");
            } else {
                out.println("<root>");
                out.println("    <result>Not found</result>");
                out.println("</root>");
            }
            out.close();
        }

First initialize the found and error booleans for later use. Since the associated Javascript AJAX Tutorial is expecting XML we set the response type to text/xml instead of the text/html used in the Subscribe servlet. Read in the membership list and convert it to a string. Then create 2 arrays to hold the member list. The second array is used to store the output array to write to the file without the unsubscribed address. Next split the string on newline and loop through the lines. Check if the email address matches the one from the unsubscribe request. If the address doesn't match add it to the newListArray. If the address is found don't add it to the new array and set the found boolean to true.

If the email address was found write out a new member list. Initialize an empty string and loop through the array appending each line to the string. Then convert the string to a byte array to write back to file. Backup the current membership list by renaming it to .old. Use the RandomAccessFile class to write out the file. If an exception was caught set the error boolean to true.

The finally block will always be executed whether or not the try block succeeded. This is where we put the output block. If there was an error return the error result. Send the success response if the address was found, otherwise send the not found response.

Introduction and Creating the First Servlet <<  1 2 3  >> Creating More Servlets
New Content