RESTful Calculator Example

Continuing along the line of our basic Quickstart Calculator example, this page will show how to create the same kind of calculator using Stripes' RESTful ActionBeans.  Let's show you the code and then break it down piece by piece:

"CalculatorRestActionBean.java"
package net.sourceforge.stripes.examples.quickstart;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.Validate;

/**
 * A RESTful Calculator Action Bean
 * 
 * @author Rick Grashel
 */
@RestActionBean
@UrlBinding( "/calculate" )
public class CalculatorRestActionBean implements ActionBean {

    @Validate(required=true) private double numberOne;
    @Validate(required=true) private double numberTwo;
 
    /**
     * This resolution will take the two numbers passed in,
     * add them together, and return the result as JSON.
     */
    public Resolution post() {
        double result = numberOne + numberTwo;
        return new JsonResolution( Double.toString( result ) );
    }
    
    public void setNumberOne( double numberOne ) { this.numberOne = numberOne; }
    public void setNumberTwo( double numberTwo ) { this.numberTwo = numberTwo; }
 
    // Below is needed for all action beans.
    private ActionBeanContext context;
    public ActionBeanContext getContext() { return context; }
    public void setContext(ActionBeanContext context) { this.context = context; }
}

At first glance, you will notice that there is almost no difference between this ActionBean and any other.  The big difference to notice is the "@RestActionBean" annotation for the class.  All Stripes RESTful services must have this annotation in order for their event handlers to be resolved according to the correct conventions.  In this situation, if a simple POST verb is placed to the "/calculate" resource, Stripes will automatically look for a corresponding post() method to execute as the handler.  If Stripes finds a corresponding handler, it will execute it.  Otherwise, Stripes will return a 404 Not Found error to the caller.  This is another situation where Stripes' convention-based approach results in very little additional code needed by a developer.

The CalculatorRestActionBean also features validation.  For this example, if the "numberOne" or "numberTwo" parameters are missing, Stripes will return a "400 Bad Request" back to the caller with a well-structured JSON response that contains any validation error message and also the field(s) to which the error(s) apply.  Just like any other Stripes ActionBean.

Now, let's take a look at a working example of an HTML page which uses this RESTful Stripes ActionBean (using jQuery):

calculator.html
<html>
    <head>
        <script src="//code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
        <script>
            $(document).ready(function () {
                $("#calculatorForm").submit(function (e) {
                    e.preventDefault(); //STOP default action
                    var postData = $(this).serializeArray(); 
                    var formURL = $(this).attr("action");
                    $.ajax({
                            url: formURL,
                            type: "POST",
                            data: postData,
                            success: function (data, textStatus, jqXHR) {
                                $("#result").html(data);
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                $("#result").html(errorThrown);
                            }
                    });
                    return false;
                });
            });
        </script>
        <title>My First Rest Action Bean (with jQuery!)</title>
        <style type="text/css">
            input.error { background-color: yellow; }
        </style>
    </head>
    <body>
        <h1>Stripes Calculator using RestActionBean</h1>
        Hi, I'm the Stripes Calculator. I can only do addition. Maybe, some day, a nice programmer
        will come along and teach me how to do other things?
        <form id="calculatorForm" action="/calculate" focus="" method="post">
            <table>
                <tr>
                    <td>Number 1:</td>
                    <td><input type="text" name="numberOne"/></td>
                </tr>
                <tr>
                    <td>Number 2:</td>
                    <td><input type="text" name="numberTwo"/></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <input type="submit" value="Add"/>
                    </td>
                </tr>
                <tr>
                    <td>Result:</td>
                    <td id="result">${actionBean.result}</td>
                </tr>
            </table>
        </form>
    </body>
</html> 

As you can see, there is nothing Stripes specific about this page at all.  It is pure HTML, uses no Stripes tags, and has no Stripes references.  When the "calculatorFom" is submitted, the jQuery submit() function will catch it.  The jQuery function will then gather the form fields and perform a standard post to the action URL specified by the form.  The result of the call will be placed in the "result" table cell beneath the form.

That's all there is to it!  

Using Stripes' native RestActionBean capabilities, there is no need to create custom Stripes plugins or interceptors to create a RESTful service.  Merely designate an ActionBean as being a "@RestActionBean" and your ActionBean is transformed into a powerful RESTful service with all of the same capabilities that any other ActionBeans have.  This example is just a small taste of the capabilities of RestActionBeans.  Continue reading the documentation to discover all of the capabilities that RestActionBeans have to offer!