Adding (or should I say Dividing) another Operation
This is great and all, but what if we wanted to build out some other
operations? Say division? Well, it turns out that's pretty straightforward.
First we make a quick addition to the JSP:
Next we add a new Handler method to the ActionBean:
public Resolution division() { result = numberOne / numberTwo; returnnew ForwardResolution("/quickstart/index.jsp"); }
The validations we defined earlier apply when the "division" event is fired,
just like when the "addition" event is fired. However, we should probably
ensure that when a division event occurs that the user isn't trying to trick
the system into dividing by zero. We could write the validation code in the
division() method if we wanted, but instead we'll add a ValidationMethod:
@ValidationMethod(on="division") public void avoidDivideByZero(ValidationErrors errors) { if (this.numberTwo == 0) { errors.add("numberTwo", new SimpleError("Dividing by zero is not allowed.")); } }
Methods which perform validation are marked with a @ValidationMethod annotation to tell
Stripes to run them prior to executing the Handler method. Unless otherwise
specified Stripes will execute validation methods for all events; in this case
we've restricted the method to be run only on division events. The method is passed
a reference to the ValidationErrors object which is used to store validation errors for the
current event.
The method checks to see if the denominator is zero and if so, creates an
instance of SimpleError to hold an error message. This works, but is rather quick and
dirty. A better approach might be to use a
LocalizableError
and provide it with the key of a message stored in the StripesResources file.