2017-06-13 22 views
0

我想能夠綁定一個數組到一個布爾型的字段(我有一個複選框和一個隱藏的字段,如果我沒有收到任何值的字段,它可以顯示默認值)。春天不允許:如何將一個數組綁定到一個布爾值在春天

binding error Field error in object 'target' on field 'documents': rejected value [true,false]; codes [typeMismatch.target.documents,typeMismatch.documents,typeMismatch.boolean,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [target.documents,documents]; arguments []; default message [documents]]; default message [Failed to convert property value of type 'java.lang.String[]' to required type 'boolean' for property 'documents'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [true,false]] 

我試着添加我自己的屬性編輯器,但似乎這個錯誤是更早引發。

ServletRequestDataBinder binder = new ServletRequestDataBinder(formBean); 
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true, 10)); 


binder.registerCustomEditor(Boolean.class, new PropertyEditorSupport() { 
    @Override 
    public void setAsText(String text) { 
     logger.debug("boolean text : " + text); 
     // setValue(type); 
    } 
}); 

binder.registerCustomEditor(String[].class, new PropertyEditorSupport() { 
    @Override 
    public void setAsText(String text) { 
     logger.debug("array text : " + text); 
     // setValue(type); 
    } 
}); 

回答

0

現在我的解決辦法是:

//autowire a ConversionService 
@Autowired 
ConversionService conversionService; 
[...] 
//set a ConversionService 
ServletRequestDataBinder binder = new ServletRequestDataBinder(formBean); 
binder.setConversionService(conversionService); 

註冊一個轉換器。我使用的是Spring Boot,在我的情況下將它註冊爲一個bean的作品。

@Component 
public class StringArrayToBolean implements Converter<String[], Boolean> { 

    protected final Logger logger = LoggerFactory.getLogger(getClass()); 

    @Override 
    public Boolean convert(String[] source) {; 
     if (source.length == 1) { 
      return source[0].equals("true"); 
     } else if (source.length > 0) { 
      for (String s : source) { 
       if (s.equals("true")) { 
        return true; 
       } 
      } 
     } 

     return false; 
    } 

} 
相關問題