java

[spring] 입력폼 배열로 받기

초초초보 2012. 8. 27. 19:53

출처 : http://blog.daum.net/gujjy/116



력폼을 배열로 받을때


============================================================

text, checkbox 는 name 을 그냥 같게 배열인덱스를 넣지 않는 경우


<input type='text' name='text' value='text1'/>

<input type='text' name='text' value='text2'/>

<input type='checkbox' name='ckhbx' value='aa'/>

<input type='checkbox' name='ckhbx' value='bb'/>

<input type='file' name='files/>

<input type='file' name='files/>


이런 식으로 만들고 

DTO 클래스에서는 아래와 같이 만들어주면 다 쓸어 담는다.

쓸어 담는줄 알았는데... file은 배열인덱스를 넣지 않으면 안들어간다.. 썩을...

파일은 아래처럼 해야 된다...

class DTO(){

    private List text;

    private List ckhbx;

    private List files;

//getter and setter

.....

}


org.springframework.web.multipart.commons.CommonsMultipartResolver

얘가 쓸어 담는 역할을 해주는데... 쩝.. 배열인덱스를 넣지 않은 것은 지원하지 않는다고...


=============================================== 

name에 배열로 명시하는 경우 

text, checkbox 는 name 을 그냥 같게 배열인덱스를 넣지 않는 경우


<input type='text' name='text[0]' value='text1'/>

<input type='text' name='text[1]' value='text2'/>

<input type='checkbox' name='chkbx[0]' value='aa'/>

<input type='checkbox' name='chkbx[1]' value='bb'/>

<input type='file' name='files[0]/>

<input type='file' name='files[1]/>


이런 식으로 만들고 

위와 다르게 기본 생성자를 정의하고 각 배열 객체를 초기화시켜준다.

그래야 

org.springframework.beans.NullValueInNestedPathException 예외를 뱉지 않는다. 


class DTO(){

    private List text;

    private List chkbx;

    private List files;

    

    public Dto(){

        text = new ArrayList();

        chkbx = new ArrayList();

        files = new ArrayList();

    }   


//getter and setter

.....

}


==============================================================================

두가지의 차이점은 아래의 경우 DTO 내에서 객체를 초기화 시켰기 때문에

getter로 가져와서 null 검사를 하지 않아도 된다는 것이다.

isEmpty()나 size()메서드를 바로 사용할 수 있다는 것이 좋다고 할까?


일단 모두가져와서 똑같은 작업을 하기 때문에 인덱스가 의미가 없어서..

어떤것이 좋다고 할지 모르겠다.