2013-02-09 3 views
0

저는 Spring 3.2와 함께 작업하고 있습니다. 전 세계적으로 double 값의 유효성을 검사하기 위해 CustomNumberEditor을 사용합니다. 유효성 확인이 실제로 수행됩니다. I 입력 1234aaa, 123aa45 등 같은 숫자가, 내가 기대하는 경우Spring에서 PropertyEditorSupport 사용자 정의하기

는 그러나 NumberFormatException가 발생하지만 그렇지 않습니다합니다. 지정된 문자열의 시작 는, 따라서 그들은 숫자와 나머지로 표현까지 구문 분석 위에서 언급 한 바와 같이 같은 값을

을 구문 분석 할 수없는 경우 워드 프로세서,

때 ParseException가 발생 말한다 그 다음에 문자열의 값은 생략됩니다.

이 문제를 방지하고 그러한 값이 입력되면 question에서 설명한대로 PropertyEditorSupport 클래스를 확장하여 자체 속성 편집기를 구현해야합니다. 다음과 같이

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 주석이 방법 안에 지정한 편집자이다. 나는 스프링 3.2을 사용하고 있기 때문에

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)); 
    } 
} 

, 나는 호기심에서 @ControllerAdvice


을 활용할 수 있으며, StrictNumericFormat 클래스의 PropertyEditorSupport 클래스에서 오버라이드 (override) 방법은 호출되지 않으며 않습니다 해당 메서드 (getAsText()setAsText()) 내부에 지정된대로 출력을 콘솔로 리디렉션하는 명령문은 서버 콘솔에 아무 것도 인쇄하지 않습니다.

나는 모든 답변을 그 question의 모든 대답에 설명했지만 어떤 것도 나를 위해 일하지 않았습니다. 내가 여기서 무엇을 놓치고 있니? 이것은 일부 XML 파일에서 구성해야합니까?

답변

1

분명히 StrictNumericFormat 참조를 전달한 곳이 없습니다. Converters

:

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

이 BTW 봄 3.X는 새로운 방식으로 달성 변환을 소개 :처럼 당신은 당신의 편집기를 등록해야

관련 문제