Wouldn’t it be cool under some circumstances to parse and render objects directly - without even knowing about path parameters?
Easily possible.
1) Let’s suppose you got an object like that:
public class Contact {
private String name;
private String email;
public String description;
public int id;
public Contact() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
2) And suppose you got a post form like that:
<form action="/contactForm" method="post">
<table class="form">
<tr>
<th><label for="name"> Name </label></th>
<td><input class="input_full" type="text" id="name" name="name" />
</td>
</tr>
<tr>
<th><label for="email"> Email </label></th>
<td><input class="input_full" type="email" id="email"
name="email" /></td>
</tr>
<tr>
<th><label for="description"> Description </label></th>
<td><input class="input_full" type="text" id="description"
name="description" /></td>
</tr>
<tr>
<th><label for="id"> ID number </label></th>
<td><input class="input_full" type="number" id="id"
name="id" /></td>
</tr>
</table>
<p>
<input type="submit" value="Send" /> <input type="reset"
value="Reset">
</p>
</form>
3) You can then parse that request simply by specifying the object in the application controller:
public Result postContactForm(Context context, Contact contact) {
return Results.html().render(contact);
}
Really simple. Ninja maps the post request form parameters directly to the object you specified. Primitive types (or their object wrapper types) will be automatically converted and mapped.
But wait - there is a bit more: You can even render the object directly via “Results.html().render(contact)”.
The corresponding Freemarker template would then look like:
<li>${contact.name}</li>
<li>${contact.email}</li>
<li>${contact.description}</li>
<li>${contact.id}</li>
“contact” is the lower camel case version of the object’s class name. And you can then access the fields (or getters / setters in case the fields are private) via “contact.name”.