簡體   English   中英

在Spring中自定義PropertyEditorSupport

[英]Customizing PropertyEditorSupport in Spring

我正在使用Spring 3.2。 為了全局驗證double值,我使用CustomNumberEditor 確實進行了驗證。

但是當我輸入一個像1234aaa123aa45等數字時,我希望拋出NumberFormatException ,但事實並非如此。 文檔說,

如果無法解析指定字符串的開頭,則會導致ParseException

因此,解析上述值,將它們表示為數字,然后省略字符串的其余部分。

為了避免這種情況,並使它拋出異常,當這些值被提供時,我需要通過擴展此問題中提到的PropertyEditorSupport類來實現我自己的Property Editor。

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


出於好奇,從不調用StrictNumericFormat類中的PropertyEditorSupport類的重寫方法,並且在這些方法( getAsText()setAsText() )中指定的將輸出重定向到控制台的語句不會在服務器控制台

我曾試圖在所有的答案中描述的所有方法的問題 ,但沒有為我工作。 我在這里錯過了什么? 這是否需要在某些xml文件中配置?

很顯然,你沒有通過StrictNumericFormat引用。 你應該注冊你的編輯器:

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

BTW Spring 3.X引入了一種實現轉換的新方法: 轉換器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM