블로그 이미지
헤이장

Notice

Recent Post

Recent Comment

Recent Trackback

calendar

1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
  • total
  • today
  • yesterday
2009. 7. 27. 20:19 Web/Framework

액션클래스가 실행되기전에 가로채서 어떤 일을 수행하는 인터셉터

우선 보면


<action name="chkLogin" class="action.CheckLoginAction">

            <interceptor-ref name="servletConfig"/>
            <interceptor-ref name="prepare"/>
            <interceptor-ref name="modelDriven"/>
            <interceptor-ref name="params"/>
            <result>main.jsp</result>
</action>


public class CheckLoginAction implements Preparable, ModelDriven<Member_Hanbit>, SessionAware {
...  생략 ...
}


모든 인터셉터는 정상적으로 작동한다.
 

그렇다면 이렇게 하면?


<action name="chkLogin" class="action.CheckLoginAction">
            <result>main.jsp</result>
</action>

public class CheckLoginAction implements Preparable, ModelDriven<Member_Hanbit>, SessionAware {
             ...  생략 ...
}

이건 또 뭔가...?
액션 클래스에 구현된 모든 인터셉터가 똑같이 정상 작동한다. 세션 조차도...
params 를 안 써도 파라메터도 받아진다


그럼 이건???


<action name="chkLogin" class="action.CheckLoginAction"> 
            <interceptor-ref name="params"/>
            <result>main.jsp</result>
</action>

public class CheckLoginAction implements Preparable, ModelDriven<Member_Hanbit>, SessionAware {
                ...  생략 ...
}

다른 인터셉터는 작동하지 않고 파라메터 인자만 받아진다....
(물론 객체가 없기때문에 위의 경우는 임시로 바로 받을 변수를 선언해주어야한다) 

※ struts.xml 에서 액션을 선언 할 경우
    인터셉터를 하나도 선언하지 않으면 알아서 구현된 모든 인터셉터를 실행해준다
    하지만.. 단 하나의 인터셉터라도 선언하게 된다면
    인터셉터의 자동 실행은 모두 사라지고 선언된 인터셉터만 실행된다 

    그렇다면 인터셉터는 귀찮게 선언할 필요가 없나 하면 그건 아닌거 같다 

만약 다른 모든 인터셉터가 실행되기 전에 prepare 에서도 전달된 파라메터 값이 필요할 때..


<action name="chkLogin" class="action.CheckLoginAction">
            <interceptor-ref name="params"/>
            <interceptor-ref name="prepare"/>
            <interceptor-ref name="modelDriven"/>
            <interceptor-ref name="params"/>
            <result>main.jsp</result>
</action>

이렇게 params 를 두번 선언해야 할 경우가 있다. // 스트럿츠2 프로그래밍 - 가메출판사 106 페이지 참고

 이럴때는 자동으로 실행되는 것으론 첫번째 params 가 실행되지 않는다 

※ 그러므로 가능하다면 모든 인터셉터를 선언해주는 것이 가장 좋을 것 같다
    꼭 액션클래스를 안봐도 사용된 인터셉터를 알 수 있게 가독성을 위해서도.

posted by 헤이장
2009. 7. 27. 13:42 Web/Framework

<Struts2 네임스페이스 에 대한 고찰> 

* 우선 경로를 /exam/~~ 이렇게 루트로 시작하게 사용하는것은 경로의 변경시 모두 변경해줘야 하는 불편이 있으므로 가능한 사용하지 않는것이 좋다는 것을 원칙으로 한다
* result 파일의 위치는 /exam/Question_Form.jsp 으로 가정한다 

첫번째 

    <package name="exam" extends="struts-default">
        <action name="to_Question_Form" class="action.exam.QuestionForm">
            <result>exam/Question_Form.jsp</result>
        </action>
    </package> 

현재위치 : 루트 안의 파일
    -> 실행명령 : location="to_Question_Form.action";
문제점 : jsp 에 js 파일이나 css, img 등 파일을 불렀을 경우 /로 시작하는 절대 경로를 적지 않는 한 경로는 대부분 틀려진다. 그리고 잘 사용하지 못하면 exam/exam/exam/exam/~~~ 을 보게 될지도 모른다
 

두번째 방법 

    <package name="exam" extends="struts-default">
        <action name="to_Question_Form" class="action.exam.QuestionForm">
            <result>Question_Form.jsp</result>
        </action>
    </package> 

현재위치 : 루트 안의 파일
     -> 실행명령 : location="exam/to_Question_Form.action";
현재위치 : exam 폴더 안의 파일
    -> 실행명령 : location="to_Question_Form.action";
문제점 : exam 폴더가 아닌곳에서 루트 또는 다른 곳에서 location="to_Question_Form.action"; 액션을 실행하면 문제없이 액션클래스가 실행되어버리고 result 에서 위치 문제로 에러를 발생시킨다

  

세번째 방법 - 네임스페이스 

    <package name="exam" namespace="/exam" extends="struts-default">
        <action name="to_Question_Form" class="action.exam.QuestionForm">
            <result>Question_Form.jsp</result>
        </action>
    </package>

 현재위치 : 루트 안의 파일
     -> 실행명령 : location="exam/to_Question_Form.action";
현재위치 : exam 폴더 안의 파일
     -> 실행명령 : location="to_Question_Form.action";
장점 : namespace 를 /exam 으로 주었기 때문에 /exam 경로가 아닌곳에서 액션이 실행되면  네임스페이스 에러로 액션의 실행을 근본적으로 막을 수 있다
네임스페이스는 항상 실행되어야 할 위치에서 액션이 실행 될 수 있도록 해준다
네임스페이스 별로 package 를 나눠두는것도 유지보수에 좋은 것 같다

posted by 헤이장
2009. 7. 27. 13:39 Web/Jsp

로그인 시 아이디 저장하기 옵션 처럼
아이디를 저장해두고 싶은 경우
쿠키를 사용 하면 된다 

쿠키 저장하기 

Cookie cookie = new Cookie("id",id);
객체 생성

cookie.setMaxAge(-1);
브라우저가 종료될때까지 유지 

cookie.setMaxAge(24*60*60);
단위는 초
24시간동안 쿠키를 유지하게 한다
이렇게 하면 일주일 한달이라도 id 값을 쿠키로 가지고 있을 수 있다 

response.addCookie(cookie);
쿠키를 응답에 저장
 

쿠키에서 불러오기 

Cookie[] cookie = req.getCookies();
int cLen = cookie.length;
for (int i = 0; i < cLen; i++) {
    if (cookie[i].getName().equals("id")) {
        System.out.println("세션에 저장된 id 값은? " + cookie[i].getValue());
    }
}

posted by 헤이장
2009. 7. 27. 13:36 Web/Jsp

< HttpSession 메서드 >

getCreationTime() - 세션 생성 시간
getLastAccessedTime() - 마지막 요청 시간
setMaxInactiveInterval() - 최대허용시간 설정 (초)
getMaxInactiveInterval() - 최대허용시간
invalidate() - 세션 제거

< 타임아웃 설정하기 > - 일정 시간 동안 요청이 없으면 세션을 제거한다 

1. DD에서 전체 세션 타임아웃 설정
      web.xml

<web-app ... >
    <servlet>

         ...
    </servlet>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

※ 단위는

  

2. 특정 세션만 타임아웃 설정

session.setMaxInactiveInterval(1800);
session.setMaxInactiveInterval(30*60);

※ 단위는

posted by 헤이장
2009. 7. 27. 13:35 Web/DesignPattern

싱글턴 패턴 - 객체가 생성되고 나면 어디서든지 다시 생성없이 사용 할 수 있도록 하는 패턴

1. static으로 자신 클래스 형의 전역변수를 만들고
getInstance() 메서드로 객체를 얻어서 사용한다
2. 멀티쓰레드 일 경우 동시에 접근해서 여러번 생성되지 않도록 동기화 시킨다

 첫번째 방법

package singleton1;
 

public class Singleton {
    private static Singleton uniqueInstance;
    public Singleton() {
    }
    public static synchronized Singleton getInstance() {
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }
}


특징 : getInstance() 의 동기화 synchronized 를 통해 한번에 한 사용자만 접근해서 객체를 생성 및 반환받는다
장점 : 객체를 처음부터 생성하지 않고 필요한 순간 생성 할 수 있다.
단점 : 매번 호출할때마다 null 비교 후 객체를 얻게 되고 동시에 많은 접근이 있을 경우 메서드의 동기화로 대기시간이 길어진다.

 두번째 방법


package singleton2;
 

public class Singleton {
    private static Singleton uniqueInstance = new Singleton();
    public Singleton() {
    }
    public static Singleton getInstance() {
        return uniqueInstance;
    }
}


특징 : 시작부터 객체를 생성해버린다.
장점 : 매번 생성되어 있는지 확인을 할 필요가 없다. 동기화로 인한 속도 저하도 없다
단점 : 객체가 무겁다면 처음부터 생성되어 있으므로 부담을 줄수도 있다

 세번째 방법


package singleton3;

public class Singleton {
    private volatile static Singleton uniqueInstance;
    public Singleton() {
    }
    public static Singleton getInstance() {
        if (uniqueInstance == null) {
            synchronized (Singleton.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}


특징 : DCL (double checking locking) 을 써서 동기화를 줄여준다. volatile 사용
       * volatile 키워드를 사용하면 멀티스레딩을 쓰더라도 uniqueInstance 변수가
          Singleton 인스턴스로 초기화 되는 과정이 올바르게 진행되도록 할 수 있습니다
장점 : 생성 부분만 동기화를 시켜서 대기시간을 줄여준다
단점 : 자바 1.4 및 이전 버젼에서는 volatile 키워드를 사용하더라도 동기화가 잘 안되는 것이 많다 고 한다

posted by 헤이장