At times it is required to add Enum values on the jsp page so that its easy to handle on the server side. To display this feature i am using spring 3.0 version.
Lets create a Java Enum Class and override some of its behavior
public enum WorkingDay {</code> Monday("Monday"), Tuesday("Tuesday"); Wednesday("Wednesday"); Thursday("Thursday"); private String description; private WorkingDay(String description) { this.description = description; } public String getValue() { return name(); } public void setValue(String value) {} public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
I just want 4 working days in a week 🙂 .
Now register a binder to the controller.
@InitBinder protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {</code> binder.registerCustomEditor(WorkingDay.class, new PropertyEditorSupport() { @Override public void setAsText(String value) throws IllegalArgumentException { if(StringUtils.isBlank(value)) return; setValue(WorkingDay.valueOf(value)); } @Override public String getAsText() { if(getValue() == null) return ""; return ((WorkingDay) getValue()).name(); } });
Set the WorkingDay object to the model object for the view. It should be in the same controller in which the above binder is registered.
@RequestMapping(value="/form", method = RequestMethod.GET) public ModelAndView showForm() { ModelAndView model = new ModelAndView("/view_my_jsp"); model.addObject("workingday", WorkingDay.values()); return model; }
Add the code in “view_my_jsp.jsp”
<form:radiobuttons path="type" items="${workinday}" />
The value of path should match the field name of the property of the command object passed.
The jsp page will contain four radio buttons.