ServletRequestDataBinder of Spring framework is usedĀ to protect unwanted biding of attributes of Bean in SimpleFormController of Spring MVC. You can define precisely which fields will be bind to the bean in view layer. Programmer used to do it by overriding the createBinder() method. Explicitly define the allowed fields in a String array and set in (servletRequestDataBinder.)setAllowedFields(allowedFields) method. Now think of a bean where you have a list of another bean. For example a bean of Course contains multiple sections.
class Bean {
.....
int id
String courseName;
List sections;
.....
}
class Section {
int id
String facultyName;
}
You have override the createBinder() method and code as follows
protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object o) throws Exception {
ServletRequestDataBinder servletRequestDataBinder = super.createBinder(request, o);
String[] allowedFields = {"courseName"};
return servletRequestDataBinder.setAllowedFields(allowedFields);
}
Now how to allow your preferred fields of section with it? Well the solution is really simple. Bean elements of a list are represent by a special format in spring. And the format is:
listName[listIndex].fieldName
So you can make your required binder by following code:
protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object o) throws Exception {
ServletRequestDataBinder servletRequestDataBinder = super.createBinder(request, o);
String[] allowedFields = {"courseName", "sections[0].facultyName"};//for 1 section
return servletRequestDataBinder.setAllowedFields(allowedFields);
}
You can run a loop for number of sections and make a list and eventually covert the list into an array list for allowing preferred fields.
By: Md. Shahjalal
Posted by Md. Shahjalal 
