복붙노트

[SPRING] Spring에서 setAllowedFields () 메소드 사용하기

SPRING

Spring에서 setAllowedFields () 메소드 사용하기

스프링 3.2.0을 사용하고 있습니다. 몇 가지 기본 요구 사항에 대한 몇 가지 사용자 정의 속성 편집기를 다음과 같이 등록했습니다.

import editors.DateTimeEditor;
import editors.StrictNumberFormatEditor;
import java.math.RoundingMode;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.joda.time.DateTime;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.propertyeditors.URLEditor;
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)
    {
        binder.setIgnoreInvalidFields(true);
        binder.setIgnoreUnknownFields(true);
        //binder.setAllowedFields(someArray);
        NumberFormat numberFormat=DecimalFormat.getInstance();
        numberFormat.setGroupingUsed(false);
        numberFormat.setMaximumFractionDigits(2);
        numberFormat.setRoundingMode(RoundingMode.HALF_UP);

        binder.registerCustomEditor(DateTime.class, new DateTimeEditor("MM/dd/yyyy HH:mm:ss", true));
        binder.registerCustomEditor(Double.class, new StrictNumberFormatEditor(Double.class, numberFormat, true));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
        binder.registerCustomEditor(URL.class, new URLEditor());
    } 
}

지금까지 많은 편집자가 등록되어 있습니다. 두 개의 DateTimeEditor 및 StrictNumberFormatEditor는 각각의 메서드를 재정 의하여 사용자 지정하여 숫자 형식 및 Joda-Time의 사용자 지정 요구 사항을 충족시킵니다.

Spring 3.2.0을 사용하고 있기 때문에 @ControllerAdvice를 이용할 수 있습니다.

악의적 인 사용자가 바운드 된 객체에 값을 삽입 할 수 없도록 setAllowedFields () 메소드로 허용되는 필드를 나열하는 것이 좋습니다.

DataBinder에 관한 문서

큰 응용 프로그램이 있고 분명히 수천 개의 필드가 있습니다. setAllowedFields ()로 모든 항목을 지정하고 나열하는 것은 지루한 작업입니다. 또한 어떻게 든 그들을 기억해야합니다.

웹 페이지를 변경하여 일부 필드를 제거하거나 필요에 따라 필드를 추가하려면 setAllowedFields () 메서드의 매개 변수 값을 수정하여 변경 내용을 반영해야합니다.

이것에 대한 대안이 있습니까?

해결법

  1. ==============================

    1.화이트리스트에 setAllowedFields ()를 사용하는 대신 setDisallowedFields ()를 사용하여 블랙리스트에 추가 할 수 있습니다. 예를 들어, petclinic 샘플 응용 프로그램에서 :

    화이트리스트에 setAllowedFields ()를 사용하는 대신 setDisallowedFields ()를 사용하여 블랙리스트에 추가 할 수 있습니다. 예를 들어, petclinic 샘플 응용 프로그램에서 :

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }
    

    순수한 보안 관점에서 볼 때 블랙리스트보다는 화이트리스트가 더 선호되지만 일부는 부담을 덜어 줄 수 있습니다.

  2. ==============================

    2.setAllowedFields ()는 웹 레이어에서 직접 엔티티 객체를 사용할 때 매우 편리합니다. 다른 방법으로, 전용 데이터 전송 객체 (DTO)를 사용할 수 있는데, 여기에서 엔티티 객체가 서비스 계층에 구축됩니다. 공장을 재사용 할 수있을뿐만 아니라 웹 컨텍스트 외부에서도 사용할 수 있습니다. 비동기 메시지의 경우 게다가 DTO 상속은 엔티티 상속을 따를 필요가 없으므로 유스 케이스의 필요에 따라 DTO 계층 구조를 자유롭게 설계 할 수 있습니다.

    setAllowedFields ()는 웹 레이어에서 직접 엔티티 객체를 사용할 때 매우 편리합니다. 다른 방법으로, 전용 데이터 전송 객체 (DTO)를 사용할 수 있는데, 여기에서 엔티티 객체가 서비스 계층에 구축됩니다. 공장을 재사용 할 수있을뿐만 아니라 웹 컨텍스트 외부에서도 사용할 수 있습니다. 비동기 메시지의 경우 게다가 DTO 상속은 엔티티 상속을 따를 필요가 없으므로 유스 케이스의 필요에 따라 DTO 계층 구조를 자유롭게 설계 할 수 있습니다.

  3. ==============================

    3.http://static.springsource.org/spring-webflow/docs/2.0.x/reference/htmlsingle/spring-webflow-reference.html#view-model

    http://static.springsource.org/spring-webflow/docs/2.0.x/reference/htmlsingle/spring-webflow-reference.html#view-model

    4.9. 명시 적으로 바인딩 지정

    바인더 요소를 사용하여보기에서 사용 가능한 모델 바인딩의 정확한 세트를 구성하십시오. 이것은 뷰 당 "허용 된 필드"집합을 제한하기위한 Spring MVC 환경에서 특히 유용합니다.

    <view-state id="enterBookingDetails" model="booking">
        <binder>
            <binding property="creditCard" />
            <binding property="creditCardName" />
            <binding property="creditCardExpiryMonth" />
            <binding property="creditCardExpiryYear" />
        </binder>
        <transition on="proceed" to="reviewBooking" />
        <transition on="cancel" to="cancel" bind="false" />
    </view-state>
    

    Y 인더 요소를 지정하지 않으면 모델의 모든 공용 특성이 뷰에 의해 Y 인딩 될 수 있습니다. 바인더 요소를 지정하면 명시 적으로 구성된 바인딩 만 허용됩니다.

    각 바인딩은 사용자 정의 방식으로 표시하기 위해 모델 특성 값의 형식을 지정하는 변환기를 적용 할 수도 있습니다. 변환기를 지정하지 않으면 모델 속성의 형식에 대한 기본 변환기가 사용됩니다.

    <view-state id="enterBookingDetails" model="booking">
        <binder>
            <binding property="checkinDate" converter="shortDate" />
            <binding property="checkoutDate" converter="shortDate" />    
            <binding property="creditCard" />
            <binding property="creditCardName" />
            <binding property="creditCardExpiryMonth" />
            <binding property="creditCardExpiryYear" />
        </binder>
        <transition on="proceed" to="reviewBooking" />
        <transition on="cancel" to="cancel" bind="false" />
    </view-state>
    

    위 예제에서 shortDate 변환기는 checkinDate 및 checkoutDate 속성에 바인딩됩니다. 사용자 지정 변환기는 응용 프로그램의 ConversionService에 등록 될 수 있습니다.

    또한 각 바인딩은 사용자가 제공 한 값이 양식 다시 게시에서 null 인 경우 유효성 검사 오류를 생성하는 필수 검사를 적용 할 수 있습니다.

    <view-state id="enterBookingDetails" model="booking">
        <binder>
            <binding property="checkinDate" converter="shortDate" required="true" />
            <binding property="checkoutDate" converter="shortDate" required="true" />
            <binding property="creditCard" required="true" />
            <binding property="creditCardName" required="true" />
            <binding property="creditCardExpiryMonth" required="true" />
            <binding property="creditCardExpiryYear" required="true" />
        </binder>
        <transition on="proceed" to="reviewBooking">
        <transition on="cancel" to="bookingCancelled" bind="false" />
    </view-state>
    

    위의 예에서 모든 바인딩이 필요합니다. 하나 이상의 빈 입력 값이 바인드되면 유효성 검증 오류가 생성되고 뷰는 해당 오류로 다시 렌더링됩니다.

  4. from https://stackoverflow.com/questions/15031049/using-the-setallowedfields-method-in-spring by cc-by-sa and MIT license