Here you will learn how to use the internal EnumConverter to get Enum's setted by reading the request parameters.
We will go through the following steps:
The CategoryType class is quite simple:
package org.vraptor.example.enumeration; public enum CategoryType { SIMPLE, COMPLEX, UNKNOWN; public String getName() { return name(); } }
We can simply use the method parameter to read the request parameter value and use the default installed converter to give us the enum:
package org.vraptor.example.enumeration; @Component("categoryType") public class CategoryTypeLogic { private CategoryType type; public void select(CategoryType type) { // do you want to do something with this type? System.out.println("Type: " + type.getName()); this.type = type; } public CategoryType getType() { return this.type; } }
Now let's create a simple result file which shows the enumeration name.
As the type variable content has been outjected we can access it through the $type expression.... $type.name will print its getName method result:
<html> The selected type was ${type.name} </html>
Now let's go to our form where the user selects the enumeration value.
We will simply show a select box and link to the business logic:
<html> <!-- using method get so you see what's going on --> <form action="categoryType.select.logic" method="get"> Category type: <select name="type"> <option value="SIMPLE">simple</option> <option value="COMPLEX">complex</option> <option value="UNKNOWN">unknown</option> </select> <input type="submit"/> </form> </html>
Another input file might use the ordinal positions... this method should be for the simple reason that if someone (not smart enough) changes the order of your enum's elements everything will stop working...
<html> <!-- using method get so you see what's going on --> <form action="categoryType.select.logic" method="get"> Category type: <select name="type"> <option value="0">simple</option> <option value="1">complex</option> <option value="2">unknown</option> </select> <input type="submit"/> </form> </html>
Now test the /categoryType/index.jsp file...
They send the name or ordinal position to the server... the EnumConverter reads it and discovers which value was selected, setting your business logic member variable to this value.
After that, the business logic method is executed and the type variable outjected.
The result.jsp file ends up showing you the type that was selected.