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

List Members

Create yet another servlet called ListMembers. This servlet will skim the surface of using DOM to build XML along with another file read/write demonstration. The ListMembers servlet is called by an AJAX get request to the servlet.

The HTML to add to index.jsp

<div id="divListMembership">
    <a href="#" onclick="ajaxListMembers()">Show List Membership</a>
</div>
<div id="divListMembershipResponse">
</div>

Import statements to add at the top of the ListMembers servlet:

import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

Set the contents of the processRequest method to:

        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String memList;
        try {
            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[] memListArray = new String[memList.split("n").length];
            memListArray = memList.split("n");
            DocumentBuilderFactory documentBuilderFactory = 
                                   DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = 
                              documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            Element rootElement = document.createElement("root");
            document.appendChild(rootElement);
            for (String s : memListArray) {
                Element e = document.createElement("member");
                e.appendChild(document.createTextNode(s));
                rootElement.appendChild(e);
            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);
            StreamResult result =  new StreamResult(out);
            transformer.transform(source, result);
        } catch(Exception ex) {
            
        } finally {
            out.close();
        }

Set the response content type to XML. Then initialize the output writer, and create a string variable memList to hold the membership list. Use the FileInputStream class to read in the membership list from disk and convert the byte array to a string. Finally close the file.

Split the string on newline. Then initialize the DOM DocumentBuilderFactory and create the DocumentBuilder object from the DocumentBuilderFactory. Use the DocumentBuilder to create a new document. Next build the root element of the document and append it to the document. Loop through the members of the list. For each member create a new element (member) and append a text node with the member information to the element. Append the member node to the root node.

Once the XML is built use the TransformerFactory to convert the DOM structure for use with the output stream. Initialize a DOMSource object with the DOM structure. This will be passed into the TransfomerFactory for output. Next setup a StreamResult object from the output stream. Use the TransformerFactory object to pass the DOM data to the output stream.

Compose Message

The last part of this tutorial will cover composing and sending a message to the list members. Sending mail with the javax.mail classes will be detailed in this servlet. Create a new servlet called ComposeMessage.

Compose message form:

 <div id="divComposeMessage">
     Compose Message:<br>
     <form id="composeMessage">
         Subject: <input type="text" id="composeSubject" name="composeSubject"/><br/>
         <textarea id="composeBox" name="composeBox" cols="80" rows="25">
         </textarea><br>
         <input type="button" name="submit" value="Send" onclick="ajaxComposeFormSubmit()"/><br/>
     </form>
 </div>
 <div id="divComposeMessageResponse">
 </div>


The import statements required for the servlet:

import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

Code for the processRequest function of the ComposeMessage servlet:

        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String memList;
        try {
            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[] memListArray = new String[memList.split("n").length];
            String[] lineSplit = new String[2];
            Properties mailProps = new Properties();
            mailProps.put("mail.smtp.host", "localhost");
            Session session = Session.getDefaultInstance(mailProps, null);
            Message msg = new MimeMessage(session);
            InternetAddress addressFrom = new InternetAddress("mailing-list@domain");
            msg.setFrom(addressFrom);
            InternetAddress[] toAddresses = new InternetAddress[memListArray.length];
            memListArray = memList.split("n");
            for (int i=0; i < memListArray.length; i++) {
                lineSplit = memListArray[i].split("t");
                toAddresses[i] = new InternetAddress(lineSplit[0]);
            }
            msg.setRecipients(Message.RecipientType.BCC, toAddresses);
            msg.setSubject(request.getParameter("composeSubject"));
            msg.setContent(request.getParameter("composeBox"), "text/plain");
            Transport.send(msg);
            DocumentBuilderFactory documentBuilderFactory =
                                   DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder =
                              documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.newDocument();
            Element rootElement = document.createElement("root");
            document.appendChild(rootElement);
            Element memListElement = document.createElement("members");
            rootElement.appendChild(memListElement);
            for (String s : memListArray) {
                Element e = document.createElement("member");
                e.appendChild(document.createTextNode(s));
                memListElement.appendChild(e);
            }
            Element subjElement = document.createElement("subject");
            String subject = new String(request.getParameter("composeSubject").getBytes());
            subjElement.appendChild(document.createTextNode(subject));
            rootElement.appendChild(subjElement);
            Element msgElement = document.createElement("message");
            CDATASection msgTxtElement = document.createCDATASection(request.getParameter("composeBox"));
            msgElement.appendChild(msgTxtElement);
            rootElement.appendChild(msgElement);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);
            StreamResult result =  new StreamResult(out);
            transformer.transform(source, result);
        } catch (TransformerException ex) {
            Logger.getLogger(ComposeMessage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ComposeMessage.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            Logger.getLogger(ComposeMessage.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }

Setup the XML response and the output writer. Initialize the string to hold the member list. Next read the membership list as before.

Setup the mail message headers. Set the mail server to use to send the message through with the Properties class. The put method is used to manipulate the settings. Next setup the session with the mail server with the javax.mail.Session class.

Create the MimeMessage object to build the complete email. Use a new InternetAddress object to create the from field and add it to the message. Split the membership list on newline to loop through. Then create an array of InternetAddresses. This will be used to store the addresses to send the message to. Loop through the list splitting each line on tab to split the name from the email address. Then append the email address to the InternetAddress array.

Once the loop completes set all the recipients as BCC so members can't harvest email addresses. Set the subject line of the message with the composeSubject from the form. Next set the content of the message with the composeBox field of the form. Use the javax.mail.Transport classes send method to trigger the actual sending of the message.

Now build the XML response to the client. As before initialize a new DocumentBuilderFactory and DocumentBuilder object to create the Document object. Create the root element and attach it to the document. Next create the membership list nested inside a members node. Loop through the membership list appending a member node with an email address the message was sent to. Then append a node for the message subject.

Use a CData field to store the contents of the message. To do this create a new CDataSection and append it to the node that should contain the CData. Next use the TransformerFactory to convert the DOM document into a format that can be sent to the output stream. This example also demonstrates multiple catch statements. Here for simplicity they all just call the built in logging functionality.

Conclusion

This tutorial is simple introduction on creating Java servlet applications with the NetBeans IDE. The code in this tutorial should not be used in a production environment as it lacks many security features mail applications should have. The goal was to demonstrate the basic concepts of servlet creation and present a few of the core features of the Java language. For more information about the concepts covered in this tutorial check out some related articles: * Java File Access Tutorial
* Javascript AJAX
* Java XML (Coming soon)

Creating the Unsubscribe Servlet <<  1 2 3
New Content