2013-02-09 19 views
0

我正在使用Spring 3.2。爲了驗證全球的雙重價值,我使用了CustomNumberEditor。驗證確實執行。在Spring中定製PropertyEditorSupport

但是,當我輸入數字如1234aaa,123aa45等等,我預計NumberFormatException被拋出,但它沒有。該文檔說,

ParseException的造成的,如果指定的字符串的開頭不能 解析

因此,如上文提到的被解析到它們被表示爲數字,其餘的這樣的值的字符串被省略。

爲了避免這種情況,並使其引發異常,當這些值被饋送時,我需要通過擴展PropertyEditorSupport類來實現我自己的Property Editor,如question中所述。

package numeric.format; 

import java.beans.PropertyEditorSupport; 

public final class StrictNumericFormat extends PropertyEditorSupport 
{ 
    @Override 
    public String getAsText() 
    { 
     System.out.println("value = "+this.getValue()); 
     return ((Number)this.getValue()).toString(); 
    } 

    @Override 
    public void setAsText(String text) throws IllegalArgumentException 
    { 
     System.out.println("value = "+text); 
     super.setValue(Double.parseDouble(text)); 
    } 
} 

我在用@InitBinder註釋標註的方法中指定的編輯器如下。

package spring.databinder; 

import java.text.DateFormat; 
import java.text.DecimalFormat; 
import java.text.Format; 
import java.text.NumberFormat; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import org.springframework.beans.propertyeditors.CustomDateEditor; 
import org.springframework.beans.propertyeditors.CustomNumberEditor; 
import org.springframework.web.bind.WebDataBinder; 
import org.springframework.web.bind.annotation.ControllerAdvice; 
import org.springframework.web.bind.annotation.InitBinder; 
import org.springframework.web.context.request.WebRequest; 

@ControllerAdvice 
public final class GlobalDataBinder 
{ 
    @InitBinder 
    public void initBinder(WebDataBinder binder, WebRequest request) 
    { 
     DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
     dateFormat.setLenient(false); 
     binder.setIgnoreInvalidFields(true); 
     binder.setIgnoreUnknownFields(true); 
     //binder.setAllowedFields("startDate"); 
     binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); 

     //The following is the CustomNumberEditor 

     NumberFormat numberFormat = NumberFormat.getInstance(); 
     numberFormat.setGroupingUsed(false); 
     binder.registerCustomEditor(Double.class, new CustomNumberEditor(Double.class, numberFormat, false)); 
    } 
} 

由於我使用Spring 3.2,我可以採取的@ControllerAdvice


出於好奇優勢,從PropertyEditorSupport類的StrictNumericFormat覆蓋方法永遠不會調用和按照這些方法(getAsText()setAsText())中指定的方式將輸出重定向到控制檯的語句不會在服務器控制檯上打印任何內容。

我嘗試了所有在question的答案中描述的所有方法,但都沒有爲我工作。我在這裏錯過了什麼?這需要配置在一些XML文件?

回答

1

顯然你沒有通過StrictNumericFormat參考。你應該註冊您的編輯器,如:

binder.registerCustomEditor(Double.class, new StrictNumericFormat()); 

BTW春3.X推出一種新的方式實現轉換:Converters

相關問題