Clean Code that Works.

주말에 해야할 포스팅.

ExtJs에 JSON 형태의 값을 리턴하기 위하여
SpringMVC에서 어떻게 값을 만들어서 리턴 해야 하는지.

필요 lib :
  • json-lib-2.2.3-jdk15.jar
  • commons-lang
  • commons-collections
  • commons-beanutils
환경
  • eclipse 3.4
  • spring 2.5
  • IE 7

컥.. 0,.0
주말에 머했지!
그냥 슝 지나갔네.. ㅠ_ㅠ

내일 점심 때 포스팅 합시다.



http://docs.jquery.com/Tutorials:Using_Ext_With_jQuery

구글 그룹에 답변 : 바로 가기

a) jquery.js
b) dimensions-plugin
c) other possible jquery-plugins you might want to use
d) the Ext jQuery Adapter script. This is in your ext-directory which you
just uncompressed earlier, at ext-1.0\adapter\jquery\ext-jquery-adapter.js
e) Include the main Ext javascript-file, ext-1.0\ext-all.js

6) Include the necessary css-eye-candy
Please note that the Ext css-files reference images inside the ext-folder,
so I wouldn't carelessly move them around.
a) The ext base css from: ext-1.0/resources/css/ext-all.css
b) Pick a theme, for Dark Vista: ext-1.0\resources\css\ytheme-vista.css
(there is also ytheme-aero.css and ytheme-gray.css, didn't try em out yet).

7) Like all l33ts just skip the tutorials and jump right into mixing jQuery
with Ext:

내일 회사 가면 해보자.

오.. 신기해.. =ㅁ=

Jquery 공부한지도 얼마 안됬는데 .... OTL.

extjs 도 번역서좀 굽신.

구글에 jquery dialog button focus 이렇게 검색 하였더니.
아래와 같은 결과가..

 Why is the dialog Close icon focused when opening the dialog?
I would like to have it not focused when the dialog opens.
Is there a way to make that happen?
Thanks,

 이렇게 질문한 사람이 있었다.
이것에 대한 답변으로


In rc5 and previous releases the logic was:
find the first tabbable element in the dialog and give it focus on
open.

In current SVN the logic is:
find the first tabbable element in the following order:
- content area
- button pane
- title bar
and give it focus on open.

This is done for accessibility to ensure that the dialog has focus
when opened.  We may change the logic after doing some testing to
focus the actual dialog div if the close button is what would receive
focus.

뭐 맨 윗줄 보면 처음 탭 이동이 가능한 엘리먼트를 다이얼 로그를 열때
포커스를 얻는다고 되어 있다.

이를 해결하기 위해 다이얼로그를 열때 포커스를 직접 지정해 주어야 한다.

You can try this:
$("#dialog").dialog({
    open: function() {
        $(this).parents('.ui-dialog').attr('tabindex', -1)[0].focus();
    }
});

이렇게.


위의 방식대로 하게 되면 버튼 자체에 포커스가 사라져 버린다.
ui.dialog.css 파일을 보면 text-align: 이 left로 되어있다. 이걸 center로 변경 하고
.ui-dialog .ui-dialog-buttonpane { text-align: center; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; }
그 밑에 라인을 보면 float: right로 되어있다. 이게 버튼 창을 오른쪽으로 밀게 되어있다.
.ui-dialog .ui-dialog-buttonpane button { float: none; margin: .5em .4em .5em 0; cursor: pointer; padding: .2em .6em .3em .6em; line-height: 1.4em; width:auto; overflow:visible; }

이렇게 하면 가운데 정렬에 (확인), (취소) 버튼 순서대로 나오고 (확인) 버튼에 포커스가 있는것을 확인 할 수 있다.


스트럿츠2 액션 요청을 전부다 ajax로 처리 하기 위하여 jquery를 도입했다.
파일 업로드 같은 경우는 스트럿츠2에 인터셉터로 통해 파일 업로드를 지원하는데.
멀티 파일 업로드는 ajax로 폼을 전송하였을 때는 값이 넘어 가지 않아서 처리하기가 곤란하다.

이전에는 프로토타입을 도입하여 ajax요청을 처리 하였는데.
멀티파일 업로드를 ajax로 처리하기 위하여 프로토타입을 걷어 내고 jquery로 ajax요청을 처리 하였다.

필요한 라이브러리
jquery.js : jquery core 라이브러리
jquery.form.js : form 을 ajax로 submit 하기 위한 라이브러리 
jquery.MultiFile.js : 멀티파일 업로드 구현을 위한 라이브러리

간단한 구현 시나리오를 살펴보면
멀티파일 업로드 뷰를 구현하고(html)
이를 전송하기 위한 폼 전송 메서드를 구현하고(javascript)
전송한걸 처리하는 actionclass를 구현하면 된다.

그럼 html 부분 부터 살펴보자.

<s:form action="fileUpload" id="fileUpload" method="post" enctype="multipart/form-data">
    <s:file name="file" label="File" id="file" cssClass="multi"/>
    <s:submit/>
</s:form>

아주 간단하다.
그냥 type="file" 인 태그에 class를 multi로 지정해 주면 된다.
일반 html 태그는 <input type="file" name="file" id="file" class="multi">로 지정해 주면 된다.

옵션으로는 class에 지정해 주거나, 속성으로 지정 가능하다.
class="multi max-4 accept-jpg|gif" => 업로드 4개로 제한, jpg, gif 제한
속성으로 지정 하는 방법은 위의 다운로드 사이트를 참고 하길 바란다.
다양한 예제가 준비 되어 있다.

여기까지는 단순히 뷰만 구현되어 있고.
이를 처리 하기 위한 ajax와 액션 클래스를 구성해야 한다.

그럼 ajax 부분 부터 살펴보자.

$(document).ready( function() {
 var options = {
         target:        '#output2',   // target element(s) to be updated with server response
         beforeSubmit:  showRequest,  // pre-submit callback
         success:       showResponse,  // post-submit callback
 
         // other available options:
         url:       'fileUpload.action'         // override for form's 'action' attribute
         type:      'post'        // 'get' or 'post', override for form's 'method' attribute
         //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
         //clearForm: true        // clear all form fields after successful submit
         //resetForm: true        // reset the form after successful submit
 
         // $.ajax options can be used here too, for example:
         //timeout:   3000
     };
 
     // bind to the form's submit event
     $('#fileUpload').submit(function() {
         // inside event callbacks 'this' is the DOM element so we first
         // wrap it in a jQuery object and then invoke ajaxSubmit
         $(this).ajaxSubmit(options);
 
         // !!! Important !!!
         // always return false to prevent standard browser submit and page navigation
         return false;
     });
});

 
// pre-submit callback
function showRequest(formData, jqForm, options) {
    // formData is an array; here we use $.param to convert it to a string to display it
    // but the form plugin does this for you automatically when it submits the data
    var queryString = $.param(formData);
 
    // jqForm is a jQuery object encapsulating the form element.  To access the
    // DOM element for the form do this:
    // var formElement = jqForm[0];
 
    alert('About to submit: \n\n' + queryString);
 
    // here we could return false to prevent the form from being submitted;
    // returning anything other than false will allow the form submit to continue
    return true;
}
 
// post-submit callback
function showResponse(responseText, statusText)  {
    // for normal html responses, the first argument to the success callback
    // is the XMLHttpRequest object's responseText property
 
    // if the ajaxSubmit method was passed an Options Object with the dataType
    // property set to 'xml' then the first argument to the success callback
    // is the XMLHttpRequest object's responseXML property
 
    // if the ajaxSubmit method was passed an Options Object with the dataType
    // property set to 'json' then the first argument to the success callback
    // is the json data object returned by the server
 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
        '\n\nThe output div should have already been updated with the responseText.');
}

컥 길다.. -_-..showRequest, showResponse는 각각 콜백 함수임으로 별다른 설명은 하지 않겠다.
동작 원리를 살펴보면 폼의 submit을 새로운 함수로 바인딩해서
submit이 jQuery.form 에서 제공하는 ajaxSubmit()으로 실행 되도록 하는것이다.
jQuery.form 역시 해당 다운로드 사이트에 보면 완벽한 예제를 제공 하고 있다.

$(this).ajaxSubmit(options);
를 통해 ajax를 요청한다.

이제 파일 업로드를 구현 해야 한다.
fileUpload.action으로 액션을 요청 하는데.
스트럿츠2에서는 파일 업로드를 위한 인터셉터(fileUpload)를 제공한다.

스트럿츠 설정 파일인 strut.xml에 다음과 같이 액션매핑을 설정한다.

<action name="fileUpload" class="tutorial.FileUpload">
         <interceptor-ref name="fileUpload"/>
         <interceptor-ref name="basicStack"/>
         <result>index.jsp</result>
</action>

그 다음에 실제 파일을 업로드할 FileUpload클래스를 작성해주면 된다.

private File[] upload;
private String[] uploadContentType;
private String[] uploadFileName;
// 각 필드 get/setter 필요    
public String execute() throws Exception
{
       // 톰캣의 임시 폴더에 올라가 있는 파일을 서버에 저장하기 위한 로직이 필요.
       return SUCCESS;
}


위와 같이 액션 클래스를 작성해주고 디버깅을 실행해 주면 upload 변수에 임시서버에 올라간 파일명을 확인 할 수 있다. 이를 가지고 실제 서버에 파일을 쓰는 로직을 작성해 주면된다.

위와 같이 작성해 주면 ajax를 통해 파일 업로드를 수행 할 수 있다.
이것을 사용한 이유는 액션을 수행하고 나서(파일 업로드 후 디비에 파일 관련 정보 저장)
새로고침을 했을 경우 액션 url이 남아 있어서 해당 액션이 다시 수행되는 경우가 발생하였기 때문에
브라우저 url을 변경하지 않고 액션을 수행하기 위하여 이를 작성하였다.

물론 내 레벨이 낮기 때문에
이 포스트 수준역시 낮은 편이며.
아마도 액션을 다시 수행하는것을 막는 방법이 struts2에 존재할 것 같다.

jquery를 사용하여 RIA 애플리케이션 개발자에게 도움이 되었으면 좋겠다.
ps. 파일 쓰는 로직 및 파일들을 다시 작성하여 war 형태로 첨부 할 예정.

파일 트리 데모

캬.. 이거 멋진데..

그런데 이걸 가져다 쓰면 한글 폴더는 열리지 않는데...

이게 왜냐 하면.. JQuery는 파라미터를 전송할 때
encodeURIComponent 로 인코딩해서 utf-8로 전송한다.

그럼 서버 측에서
받아서 쓰면 되는데...

파일 트리를 쓰기 위해선 jqueryFileTree.js 파일을 수정해야 한다.
왜냐!!!
저 파일에서는 encodeURIComponent인코딩이 아니라 escape()로  인코딩을 하기 때문에..
escape()와 encodeURIComponent()의 차이점은..
escape는 조금만 변화하고 encodeURIComponent는 많이 -ㅅ-...

여튼 jqueryFileTree.js 파일을 열어 보면 escape를 두번 쓰고 있을 것이다.
이걸 encodeURIComponent로 바꿔주면.. 무리없이 트리메뉴를 쓸 수 있다.

오...신기해 -ㅅ-...



http://www.dehats.com/drupal/?q=node/36

여기 블로그에 나와있는 구성도 입니다.
이거 생각보다 어렵내요...
영문이라서 좀 다가가기도 어렵고.. 패턴이..ㅎㄷㄷ

일단 기본적으로 MVC 패턴이고,,싱글톤, 프록시, 커맨드, 퍼사드 패턴 등등..
디자인 패턴공부를 약간하긴 했지만 이건 뭐...-ㅁ-;;
이거 마스터하면 위 패턴은 정말 쉬울듯....


블로그 쥔장은 전체적으로 pureMVC를 추천 하는 듯 하고..
마지막에 나와있는 글을 보면..

Debugging. Singletons can mean hell when it's time to debug. PureMVC uses less Singletons than Cairngorm.

ㅎㄷㄷㄷㄷㄷ

그냥 이래 저래 공부하면서 로그인 구현 튜토리얼을 만들어 볼까 ..
뭐 영문 사이트 찾아 보면 많이 있고 pureMVC 사이트 가면 있으면서도..

영어로 되서 어려우니 겸사겸사 공부할겸 .. =ㅁ=..

천천히 조금씩 작성해 봐야지. 으케케케


대략 위와 같은 모습으로...

티스토리 블로그 페이징 처럼 해보고 싶었습니다.

 

전체 페이지를 구해와서 이를 10개씩 보여주고

나누어서 페이징을 구분 하였습니다.

이전, 이후 버튼을 추가 하여 이동 가능 하고

직접 페이지를 선택해서 이동 가능 합니다.

페이지는

5페이지가 넘을 경우

1 | ... 페이지 |...| 마지막 페이지

이런 형식으로 보여주게 되잇고 5페이지씩 보여지게 되어 있습니다.

현제 페이지는 위 스크린 샷 처럼 빨간 색으로 나타 나게 되어있습니다.

 

자 이제 소스를 보면...

디비 부분은 생략 하였습니다.

으하 복잡 합니다 ;ㅁ;

페이징은 어플리케이션 컨트롤 바에 만들었습니다.

이전, 이후 버튼은 기본 컨트롤 바(navBar)에 있고

내부에 어플리케이션 컨트롤 바(pageBar)를 한개 더 추가해서

거기다가 숫자 페이징을 적용 했습니다.

 

페이지를 이동 할 때마다 setPageBar()를 호출해서 pageBar를 다시 그리는게 핵심포인트!!!

소스 설명은.. 쉬어서 하지 않겠습니다 ;ㅁ;

 

리팩토링 안했습니다. ;ㅁ;

보여줄 페이지를 수정 하기 위해서는 수작업을 해야 합니다. (심볼릭 정수로 치환하세요 ;ㅁ;)

나중에 컴포넌트로 배포 가능 해지면 올려보겠습니다. ㅜ_ㅠ


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

간단한 리팩토링을 했습니다.

보여줄 페이지를 심볼릭 정수로 -ㅁ-..viewPage

그리고 페이지 만드는 과정에서 중복이 있길래 이를

makePage()라는 함수로 뽑아서 만들었습니다.

덕분에 소스가 줄어들고 약간 읽기 쉽게 되었습니다.

5페이지 이상일때만

1 | 페이지 | ... 마지막 페이지

이렇게 보이도록 수정했습니다.

스샷 보면 5페이지 이하 인데도

.... | 5 이렇게 되어있었습니다.


private var totalPage:int;
private var currentPage:int;
private var _label:Label;
private var _vRule:VRule;

private function setPageBar():void {
    totalPage = noticeList.getTotalPage() + 1;
                currentPage = noticeList.getCurrentPage();
               
                var viewPage:int = 5;
                var i:int;
               
                var dotLabel:Label = new Label();
                dotLabel.text = "...";
                var vRule:VRule = new VRule();
                vRule.height = 10;
                var firstLabel:Label = new Label();
                firstLabel.text = "1";
                firstLabel.addEventListener(MouseEvent.CLICK, labelClickEvent);
                var lastLabel:Label = new Label();
                lastLabel.text = totalPage.toString();
                lastLabel.addEventListener(MouseEvent.CLICK, labelClickEvent);
               
                if (totalPage > viewPage) {
                    if (currentPage < viewPage) {
                        for (i = 1; i < viewPage + 1; i++) {
                            makePage(i);               
                        }
                    } else if (currentPage >= viewPage) {
                        pageBar.addChild(firstLabel);
                        pageBar.addChild(vRule);
                        pageBar.addChild(dotLabel);
                        vRule = new VRule();
                        vRule.height = 10;
                        pageBar.addChild(vRule);
                        for (i = (currentPage - 1); i < (currentPage + 4); i++) {
                            makePage(i);       
                        }
                    }
                } else {
                    for (i = 1; i < totalPage; i++) {
                        makePage(i);
                    }
                }
               
                if (totalPage == currentPage + 1) {
                    lastLabel.setStyle("color", "Red");
                    pageBar.addChild(lastLabel);
                } else if (totalPage < viewPage + 1){
                    pageBar.addChild(lastLabel);
                } else {
                    dotLabel = new Label();
                    dotLabel.text = "...";
                    pageBar.addChild(dotLabel);
                    vRule = new VRule();
                    vRule.height = 10;
                    pageBar.addChild(vRule);
                    pageBar.addChild(lastLabel);
                }
   }

// 페이지 선택시 이동 하기 위해서 만들었습니다.
   private function labelClickEvent(event:MouseEvent):void {
    var page:int = parseInt(event.target.text, 0);
    noticeList.movePage(page);
    pageBar.removeAllChildren();
    setPageBar();
   }

// 페이지 만드는 함수

private function makePage(i:int):void {
                _label = new Label();
                _label.text = i.toString();
               
                if (i - 1 == currentPage) {
                    _label.setStyle("color", "Red");
                }
                if (i > totalPage - 1) return;
                   
                _label.addEventListener(MouseEvent.CLICK, labelClickEvent);
                _vRule = new VRule();
                _vRule.height = 10;
                pageBar.addChild(_label);
                pageBar.addChild(_vRule);       
            }


// 이전, 이후 버튼 클릭시 사용 하기 위해서 만들었습니다.   
   private function buttonDownHandler(event:FlexEvent):void {
    var type:String = event.target.label;
    if (type == "Previous") {
     noticeList.previousPage();
     pageBar.removeAllChildren();
     setPageBar();
     nextBtn.enabled = true;
     if (noticeList.getCurrentPage() == 0) {
      previousBtn.enabled = false;      
     }
    } else if (type == "Next") {
     noticeList.nextPage();
     pageBar.removeAllChildren();
     setPageBar();
     previousBtn.enabled = true;
     if (noticeList.getCurrentPage() == noticeList.getTotalPage()) {
      nextBtn.enabled = false;      
     }
    }
   }

    }
   }

그냥 게임 하면서 쓸려고 만듬 -_-


실행화면


AIR 공부할겸 겸사겸사 만든 RSS READER 프로그램.