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

Introduction to NetBeans and Glassfish

Glassfish is an open source Java EE 5 application server developed by Sun Microsystems. Included in the Java and All bundles of the NetBeans IDE also from Sun. Java servlets, published in Glassfish (or Apache Tomcat) provide a portable framework to drive dynamic web content. This tutorial demonstrates how to create a basic web application with a mix of simple HTML forms, AJAX (Javascript Introduction to AJAX companion), and Java servlets using the NetBeans IDE and Glassfish application server. The code here isn't intended for production uses, just to demonstrate the basics of creating a basic web application with NetBeans deployed in Glassfish 2.1.

The first thing to do is create a NetBeans project. Click the create new project icon (or Ctrl+Shft+N) then select Java Web and Web application. Click next and give the project a name, this tutorial is using MailingList. Click next. Select the version of the Glassfish application server to deploy the project under and the version of Java to use. Click finish to create and open the application. This will create the project and open the index.jsp in the editing pane.

Setup HTML & Javascript

For an explanation of the HTML and AJAX javascript to submit the forms see the companion article Javascript Introduction to AJAX. Put this code in the index.jsp replacing the default hello world html.

     <title>Join mailing list</title>
     <link type="text/javascript" href="ajax.js"/>
 <div id="form">
     <form name="ajaxTest">
         Name: <input type="text" name="name"/><br/>
         EMail Address: <input type="text" name="email"/><br/>
         <input type="button" name="submit" value="Subscribe" onclick="ajaxSubscribeFormSubmit()"/><br/>
 <div id="divResponse">
     Click the subscribe button to join the list

Now create the javascript file containing the ajax to make request to the servlet. Right click on Web Pages under the MailingList project in the right pane, select new, and click on javascript file. For the file name enter ajax, leave the rest of the fields default, and click finish. NetBeans will automatically append the file extension. Enter the following javascript into ajax.js.

 function ajaxSubscribeFormSubmit() {
     var xmlHttp;
     if (window.XMLHttpRequest) {
         xmlHttp = new XMLHttpRequest();
     } else if (window.ActiveXObject) {
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
     } else {
         document.write("browser not supported");
     xmlHttp.onreadystatechange=function() {
         if (xmlHttp.readyState == 4) {
             var html = document.getElementById("divResponse");
             html.innerHTML = xmlHttp.responseText;
     var name = document.getElementById("name").value;
     var email = document.getElementById("email").value;
     var queryString = "?name=" + name + "&email=" + email;"GET","Subscribe" + queryString,true);

Creating a servlet

Time to create the logic to process the AJAX request. Right click on the project select new and click new servlet. Each servlet is a java class, call this class Subscribe. Also you need to select a package for this class. For this simple project just put everything in a package called list. Click finish and NetBeans will create the required hooks and open the class file for the servlet. Add an import line 'impomrt*;' at the top of the file with the rest of the import statements NetBeans includes. This gives us access to the File classes we're going to use.

Replace the code in processRequest with the following.

     PrintWriter out = response.getWriter();
     String email = request.getParameter("email");
     try {
         if (!checkMemberList(email)) {
             addMember(email, request.getParameter("name"));
             out.print(email + " has been subscribed to the list");
         } else {
             out.print(email + " is already a member of the list");
     } catch (Exception ex) {
         out.print("Unable to add " + email + " to the list");
     } finally { 

First we set the output content type and character set and open the Writer. The email address is used in numerous places so store it in a string for easy access. Since the focus of this tutorial is creating servlets, file access, and supplementing the Javascript AJAX tutorial the try/catch block is just setup as a giant catch all for the exceptions that might happen. This is not how you should code in production.

Next check to make sure the submitter isn't already a member of the list. The checkMemberList function will be covered soon. If not a member call the addMember function and print that the address has been subscribed. The successful subscription message will not be printed if an exception happens adding the member. Add the following addMember method to after processRequest.

    private void addMember(String email, String name) throws FileNotFoundException, IOException {
            String newMember = email + "t" + name + "n";
            byte[] b = newMember.getBytes();
            File outputFile = new File("/tmp/membership_list.txt");
            RandomAccessFile fileOut = new RandomAccessFile(outputFile, "rw");

The newMember string holds the line that will be appended to file. When writing to files you use byte arrays so convert the string into a byte array. Open the membership list file in read/write RandomAccessMode and seek to the end of the file. Write the byte array containing the new line and close the file.

Before you can check if an address is in the membership list you have to read the file. Below newMember add the following method.

    private String readMemberList() throws FileNotFoundException, IOException {
        String ret = null;
        File readFile = new File("/tmp/membership_list.txt");
        if (!readFile.exists()) {
        FileInputStream in = new FileInputStream(readFile);
        byte bt[] = new byte[(int)readFile.length()];;
        ret = new String(bt);

First setup the string to return (ret). Next open the membership list file for reading. Read in membership list file into byte array, and convert byte array into a new string. Finally close the file and return the string.

    public boolean checkMemberList(String email) throws FileNotFoundException, IOException {
        String memList = readMemberList();
        String[] line = new String[2];
        String[] memListArray = new String[memList.split("n").length];
        memListArray = memList.split("n");
        for (int i=0; i < memListArray.length; i++) {
            line = memListArray[i].split("t");
            if(line[0].equalsIgnoreCase(email)) {

Read in the membership list with readMemberList(). Initialize a string array, line, with 2 fields. This is used to store the output of the tab split of the line. Then initialize a string array, memListArray, to hold the lines of the membership list file. Loop through the memListArray string array, split each line on a tab, and do a case insensitive match of the first field against the email address passed to the function. If the email address matches the function returns true otherwise after exhausting lines of the file the loop exits and false is returned.

Time to do the initial deployment in Glassfish. Make sure everything is saved then right click on the project and click deploy. Let NetBeans load everything up then browse to http://localhost/MailingList/index.jsp. Fill out the form and submit. Check the file and see if it worked as expected. When you're ready to close stop Glassfish click the Stop button in the bottom pain. It's the red square button with the smaller white square inside.

 1 2 3  >> Creating the Unsubscribe Servlet
New Content