Spring MVC + Enum + PropertyEditorSupport

Problem:
when we have enum values to display on the form:select tag. Sometimes and it will hits the problem like cannot convert from the XX.Type to YY.Type.

In order to solved this problem. i’d added a custom editor to convert back the data. Below is a sample example.

StatusTypeEditor.java

package com.loongest.editor;
import java.beans.PropertyEditorSupport;
import com.loongest.domain.StatusType;
public class StatusTypeEditor extends PropertyEditorSupport {

    @Override
    public String getAsText(){        
           return super.getAsText();
    }

    @Override  
    public void setAsText(String text) throws IllegalArgumentException 
    {
          int  c = 0;
          try {
              c = Integer.parseInt(text); 
          } catch (NumberFormatException e)  { 
              // print error 
          }
      
          switch (c) {
                case 1: 
                     this.setValue(StatusType.COMPULSORY); 
                     break;
                case 2: 
                     this.setValue(StatusType.OPTIONAL); 
                     break;
                case 3: 
                     this.setValue(StatusType.NONE_REQD); 
                     break;
                default: 
                     this.setValue(""); 
                     break;
          }                
    }  
}

StatusType.java

public enum StatusType 
{
      COMPULSORY(1),
      OPTIONAL(2),
      NONE_REQD(3);

      private final int value;

      private StatusType(int value) {
               this.value = value;
      }

      public int getValue() {
               return value;
      }
}

Finally add property binding to your controller

@InitBinder
public void initBinder(HttpServletRequest requst, ServletRequestDataBinder binder) 
{
    binder.registerCustomEditor(StatusType.class, 
               new EnrollOrderStatusTypeEditor());

    binder.registerCustomEditor(Location.class, new LocationEditor());
 }

JSP example

<form:select path="status" multiple="false">
       <form:option value="" label=" Please select one "/>
       <form:options items="${statusMap}" />
</form:select>
Spring MVC + Enum + PropertyEditorSupport

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.