2013-02-20 14 views

risposta

2

Sì, si potrebbe sempre farlo .Primavera hanno una CustomNumberEditor che è un editor di proprietà personalizzabile per ogni sottoclasse Numero come Integer, Long, Float , Double.It è inserito di default per BeanWrapperImpl, ma, può essere ignorato registrando esempio personalizzato di esso come editor.It personalizzato significa che si potrebbe estendere una classe come questa

public class MyCustomNumberEditor extends CustomNumberEditor{ 

    public MyCustomNumberEditor(Class<? extends Number> numberClass, NumberFormat numberFormat, boolean allowEmpty) throws IllegalArgumentException { 
     super(numberClass, numberFormat, allowEmpty); 
    } 

    public MyCustomNumberEditor(Class<? extends Number> numberClass, boolean allowEmpty) throws IllegalArgumentException { 
     super(numberClass, allowEmpty); 
    } 

    @Override 
    public String getAsText() { 
     //return super.getAsText(); 
     return "Your desired text"; 
    } 

    @Override 
    public void setAsText(String text) throws IllegalArgumentException { 
     super.setAsText("set your desired text"); 
    } 

} 

E poi registrarlo normalmente in voi regolatore :

@InitBinder 
    public void initBinder(WebDataBinder binder) { 

     binder.registerCustomEditor(Float.class,new MyCustomNumberEditor(Float.class, true)); 
    } 

Questo dovrebbe fare l'operazione.

+0

Grazie, funziona come il fascino –

+0

Il tuo benvenuto ... –

3

Definire un subclsss di CustomNumberEditor come

import org.springframework.beans.propertyeditors.CustomNumberEditor; 
import org.springframework.util.StringUtils; 

public class MyCustomNumberEditor extends CustomNumberEditor { 

    public MyCustomNumberEditor(Class<? extends Number> numberClass) throws IllegalArgumentException { 
     super(numberClass, true); 
    } 

    @Override 
    public void setAsText(String text) throws IllegalArgumentException { 
     if (!StringUtils.hasText(text)) { 
      setValue(0); 
     }else { 
      super.setAsText(text.trim()); 
     } 
    } 

} 

Poi nella classe controllore (creo un BaseController per tutti i miei controllori di applicazione, ho bisogno di questo comportamento per tutti i tipi primitivi numerici nella mia richiesta, così ho semplicemente definiscilo nel mio BaseController), registra i raccoglitori per i vari tipi primitivi. Si noti che il parametro costruttore di MyCustomNumberEditor deve essere una sottoclasse di Number, anziché un tipo di classe primitivo.

@InitBinder 
public void registerCustomerBinder(WebDataBinder binder) { 
    binder.registerCustomEditor(double.class, new MyCustomNumberEditor(Double.class)); 
    binder.registerCustomEditor(float.class, new MyCustomNumberEditor(Float.class)); 
    binder.registerCustomEditor(long.class, new MyCustomNumberEditor(Long.class)); 
    binder.registerCustomEditor(int.class, new MyCustomNumberEditor(Integer.class)); 
....  
} 
Problemi correlati