Here goes formBackingObject API
retrieve a backing object for the current form from the given request
Some scenarios
- Avoids NullPointerException when traversing nested path
...
public class Command {
private NestedClass nestedPath;
// getter's and setter's
}
Notice above nestedPath field has not been initialized. So if you try to retrieve its value on the form such as
<spring:form path="nestedPath.someProperty"/>
Because nestedPath has not been initialized, You will get NullPointerException when traversing some nestedPath property. To avoid NullPointException, overrides formBackingObject
public Object formBackingObject(HttpServletRequest request) throws Exception {
Command command = new Command();
command.setNestedPath(new NestedClass());
return command;
}
You submit the identifier of some command (usually by using GET method) to allow users to update it later
public Object formBackingObject(HttpServletRequest request) throws Exception {
if(request.getMethod().equalsIgnoreCase("GET")) {
return commandRepository.findById(Integer.valueOf(request.getParameter("id")));
}
}
And referenceData API
create a reference data map for the given request
You use referenceData to create data used by your form, for instance, a list of categories
protected Map referenceData(HttpServletRequest request) throws Exception {
return new ModelMap().addAttribute(categoryRepository.findAll());
}
On the form
<label>Select category</label>
<form:select path="category">
<form:option label="Select category" value=""/>
<form:options items="${categoryList}"
itemLabel="WHICH_PROPERTY_OF_CATEGORY_SHOULD_BE_USED_AS_LABEL"
itemValue="WHICH_PROPERTY_OF_CATEGORY_SHOULD_BE_USED_AS_VALUE"/>
</form:select>