Broadcast on Broadcast off
The Documentation for Project Zero has moved. Please update your bookmarks to: http://www.projectzero.org/documentation/
Table of
Contents...
Hide
 

To do list Part I - Simple to do

In this tutorial, we'll discuss the steps needed to create a simple Zero application to manage a to do list. To start with, we'll create a simple single user application. The data will be held in memory and will not be persistent. In the later tutorials, we will enhance the application to use a database for persistent storage.

The following concepts are covered in this tutorial:

  • Directory structure
  • Global context
  • File access from the public folder
  • HTTP request handlers in a Groovy template

Creating an empty Zero application

We'll begin by creating an empty Zero application to use for developing our "to do list" application. This step assumes that you have downloaded the Project Zero package.

  1. Open a Command Prompt window.
  2. Change the current directory to <zerohome>, (assuming that zerohome is the directory where you unzipped the Zero package).
  3. Type zero create simpletodo .
  4. Change the current directory to <zerohome>/apps/simpletodo .

Working with the structure of a Zero project

Let's look into what a zero project contains, by default. Zero uses conventions that reduce the amount of configuration necessary to develop an application. We will now talk about how those conventions relate to the structure of a zero application.

  • java: contains Java source code
  • public: is analogous to the document root of a web server. It contains web content such as html and javascript files.
  • app:
    • resources: contains the resources that are to be accessed RESTfully.
    • views: contains groovy templates that are used for response rendering.
    • errors: contains error pages
    • scripts: contains scripts that only contain business logic and are not web resources.
  • config: contains the configuration files for the Zero project.
  • lib: contains local .jar and .zip files included in the project.
  • logs: contains logs and traces.
  • reports: contains reports generated by the dependency management system.
  • export: default location for packaged applications (created after package or export command)

Adding to do list handling to the application

To create our to do list application, we will use a Groovy file to handle requests from the browser and service them accordingly. Groovy is an agile and dynamic language which builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk. If you are not familiar with Groovy, you can get more information at the Groovy Web site.

First, we'll use the following steps to create the Groovy file:

  1. Change the current directory to <zerohome>/apps/simpletodo/public
  2. Using your favorite text editor, create and edit the todo.groovy file.
    Note: The file is in the public folder. The public folder in a Zero application is similar to the document root of a Web server. However, there are some special handling rules for files placed in this folder. For more information, see the File serving article.
  3. Add the following content to the todo.groovy file:

    /*
     * ============================================================================
     * (C) Copyright IBM Corporation 2006, 2007.  All Rights Reserved.
     * 
     * You may only copy, modify, and distribute these samples internally.
     * These samples have not been tested under all conditions and are provided
     * to you by IBM without obligation of support of any kind.
     *
     * IBM PROVIDES THESE SAMPLES "AS IS" SUBJECT TO ANY STATUTORY WARRANTIES THAT
     * CANNOT BE EXCLUDED. IBM MAKES NO WARRANTIES OR CONDITIONS, EITHER EXPRESS
     * OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR
     * CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
     * NON-INFRINGEMENT REGARDING THESE SAMPLES OR TECHNICAL SUPPORT, IF ANY.
     * ============================================================================
     */
    
       def todos  = app.todos.get();
       if (todos == null) {
          todos = [];
       }
    
       if (request.method.get().equals('POST')) {
          def action = request.params.action.get();
          if (action.equals("Add")) {
             def items = request.params.item.get();
             logger.FINEST {"adding items=$items"};
             if (null != items){
                 item = zero.util.XMLEncoder.escapeXML(items);
                 if (null != item && item.size() > 0)
                    todos.add(item);
                 logger.FINEST {"items=$todos"};
             }
          } else {
             def selected = request.params.todos['*'];
             logger.FINEST {"removing items=$selected"};
             for (i in selected)
                todos.remove(i);
             logger.FINEST {"items=$todos"};
          }
          app.todos = todos; 
       }
    
    writer = request.writer.get()   
       
    writer.write '''   
    <html>
    <head>
       <title>Simple Todo List</title>
    </head>
    <body>
       <b>Your todo items:</b>
       <br>
       <form name="input" action="/todo.groovy" method="POST">
    '''
      
    todos.each { writer.write "<input type=\"checkbox\" name=\"todos\" value=\"" + it + "\"> "+it+"<br>" } 
    writer.write '''
          <br>
          <input type="text" name="item">
          <input type="submit" name="action" value="Add">
          <input type="submit" name="action" value="Delete">
       </form>   
    </body>
    </html>
    '''
    
  4. Save the todo.groovy file.

That is all you need to do to create your to do application! Your to do application is ready to try out.

Working with the todo.groovy file

The Zero concept that needs to be explained here is the global context. Global context holds all of the state information for a Zero application. For example, a parameter of the HTTP request is accessed using the request.params.item.get() call. There are various zones defined in the global context that logically divide the information. In the todo.groovy file, we deal with the app zone and the request zone. These two zones store information about the application and the request respectively. For more information about the global context, see the Global Context article.

Running the simpletodo application

To run your simpletodo application, use the following steps:

  1. Change the current directory to <zerohome>/apps/simpletodo
  2. Type zero make to compile.
  3. Type zero run to run the simpletodo application.
  4. Using your browser, go to the http://localhost:8080/todo.groovy site.

    The following example shows some sample output:

    SampleOutput.JPG

Adding template handling to the application

We just ran the simple to do list application. Now, lets make some changes to it to incorporate a groovy template and take some of the HTML generation away from the groovy script.

First, we'll use the following steps to create the Groovy template:

  1. Change the current directory to <zerohome>/apps/simpletodo/app/views
  2. Using your favorite text editor, create and edit the todo.gt file.
  3. Add the following content to the todo.gt file:

    <% 
    /*
     * ============================================================================
     * (C) Copyright IBM Corporation 2006, 2007.  All Rights Reserved.
     * 
     * You may only copy, modify, and distribute these samples internally.
     * These samples have not been tested under all conditions and are provided
     * to you by IBM without obligation of support of any kind.
     *
     * IBM PROVIDES THESE SAMPLES "AS IS" SUBJECT TO ANY STATUTORY WARRANTIES THAT
     * CANNOT BE EXCLUDED. IBM MAKES NO WARRANTIES OR CONDITIONS, EITHER EXPRESS
     * OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR
     * CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
     * NON-INFRINGEMENT REGARDING THESE SAMPLES OR TECHNICAL SUPPORT, IF ANY.
     * ============================================================================
     */
    %>
    <html>
    <head>
       <title>Simple Todo List</title>
    </head>
    <body>
       <b>Your todo items:</b>
       <br>
       <form name="input" method="POST">
          <% app.todos.each { %>
             <input type="checkbox" name="todos" value="<%=it%>"> <%=it%> <br> 
          <% } %>
          <br>
          <input type="text" name="item">
          <input type="submit" name="action" value="Add">
          <input type="submit" name="action" value="Delete">
       </form>   
    </body>
    </html>
    
    
  4. Save the todo.gt file.
  5. To make use of this template that we just created, we need to modify our todo.groovy. Replace the contents of public/todo.groovy with the following:

    /*
     * ============================================================================
     * (C) Copyright IBM Corporation 2006, 2007.  All Rights Reserved.
     * 
     * You may only copy, modify, and distribute these samples internally.
     * These samples have not been tested under all conditions and are provided
     * to you by IBM without obligation of support of any kind.
     *
     * IBM PROVIDES THESE SAMPLES "AS IS" SUBJECT TO ANY STATUTORY WARRANTIES THAT
     * CANNOT BE EXCLUDED. IBM MAKES NO WARRANTIES OR CONDITIONS, EITHER EXPRESS
     * OR IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR
     * CONDITIONS OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
     * NON-INFRINGEMENT REGARDING THESE SAMPLES OR TECHNICAL SUPPORT, IF ANY.
     * ============================================================================
     */
    
     def todos  = app.todos.get();
     if (todos == null) {
        todos = [];
     }
    
     if (request.method.get().equals('POST')) {
        def action = request.params.action.get();
        if (action.equals("Add")) {
           def items = request.params.item.get();
           logger.FINEST {"adding items=$items"};
           if (null != items){
               item = zero.util.XMLEncoder.escapeXML(items);
               if (null != item && item.size() > 0)
                  todos.add(item);
               logger.FINEST {"items=$todos"};
           }
        } else {
           def selected = request.params.todos['*'];
           logger.FINEST {"removing items=$selected"};
           for (i in selected)
              todos.remove(i);
           logger.FINEST {"items=$todos"};
        }
        app.todos = todos; 
    }
    
    request.view = 'todo.gt';
    zero.core.views.ViewEngine.render();
    
    
    
  6. Run the application again just like you did before !

Next >>>

r15 - 24 Oct 2007 - 17:53:03 - binhn
Syndicate this site RSS ATOM
Copyright 2007 © IBM Corporation | Privacy | Terms of Use | About this site