1. struts2의 인터셉터 (프레임 기능 코어)
1. 필터 대 인터셉터
필터 대 인터셉터 함수는 한 가지입니다. 필터는 요청 및 응답을 필터링 할 수있는 서블릿 사양의 기술입니다.
인터셉터는 struts2 프레임 워크의 기술로, AOP (섹션 지향) 프로그래밍 아이디어를 구현하는데, 이는 플러그 가능하며 특정 동작 방법에 액세스하기 전 또는 후에 가로 채기 할 수 있습니다.
인터셉터 스택 : 인터셉터를 특정 순서대로 체인에 연결하십시오. 인터셉터 방법에 액세스 할 때 Struts2 인터셉터 체인의 인터셉터는 이전에 정의한 순서대로 순서대로 호출됩니다.
STRUTS2 실행 원칙 - 기본 분석
2. 사용자 정의 인터셉터
struts2는 인터셉터 인터페이스 인터셉터 인터페이스를 정의합니다.
인터셉터 인터페이스에는 세 가지 추상 방법이 있습니다
• INT :이 방법은 인터셉터가 생성 된 직후에 호출되며 인터셉터 수명 동안 한 번만 호출됩니다. 이 방법에서 관련 리소스를 초기화 할 수 있습니다.
• Interept :이 방법은 조치 요청이 가로 채울 때마다 한 번 호출됩니다.
• 파괴 :이 방법은 인터셉터가 파괴되기 전에 호출되며 인터셉터의 수명주기 동안 한 번만 호출됩니다.
Struts는 프로그래머가 등록한 각 인터셉터의 인터셉트 방법을 행동으로 호출합니다. 인터셉트 메소드가 호출 될 때마다 Struts는 ActionInvocation 인터페이스의 인스턴스를 전달합니다.
ActionInvocation : 주어진 작업의 실행 상태를 나타냅니다. 인터셉터는이 클래스의 객체에서 동작과 관련된 액션 객체 및 결과 객체를 얻을 수 있습니다. 인터셉터의 자체 작업을 완료 한 후 인터셉터는 액션 처리 프로세스의 다음 단계로 ActionInvocation 객체의 호출 메소드를 호출합니다.
ActionInvocation 객체의 addPreresultListener 메소드를 호출하여 하나 이상의 전두리스트 리스너 리스너를 "교환"할 수 있습니다. 이 리스너 객체는 작업이 실행 된 후 작업 결과를 실행하기 전에 무언가를 할 수 있습니다.
사용자 정의 인터셉터 단계 :
에이. com.opensymphony.xwork2.interceptor.interceptor 인터페이스 또는 상속을 구현하기 위해 클래스를 작성하십시오.
com.opensymphony.xwork2.interceptor.AbStractInterceptor 클래스. (어댑터 모드), 일반적으로 AbstractInterceptor를 상속하기로 선택합니다 (인터셉터는 메모리에 있습니다). Abstractinterceptor 클래스는 인터셉터 인터페이스를 구현하기 때문입니다. Init and Destroin에 대한 빈 구현을 제공합니다
2 개의 인터셉터를 interceptemo1과 interceptemo2로 작성하십시오
package com.isheima.interceptor; import com.opensymphony.xwork2.actioninvocation; import com.opensymphony.xwork2.interceptor.abstract interceptordemo1은 AbstractInterceptor를 확장합니다. {//이 메소드가 공개 문자열 인터셉트 (ActionInvocation intercept)에 액세스 할 때마다 호출됩니다. 문자열 rtvalue = invoction.invoke (); // release, 왜 문자열이 여기에서 돌아 오는가? 최종 결과는 동작의 결과를 반환하고 동작의 결과는 문자열 유형 System.out.println ( "intercept demo1")이기 때문입니다. rtvalue를 반환하십시오. }} 패키지 com.itheima.interceptor; import com.opensymphony.xwork2.actionInvocation; import com.opensymphony.xwork2.interceptor.ABStractInterceptor; import com.opensymphony.xwork2.interceptor.preresultlistore.preresultlisteDemo2는 Access The Mocation이 될 것입니다. 인터셉트 (ActionInvocation invocation)는 예외를 {// invocation.addpreresultListener (new preresultListener () {// public void beforeSult (ActionInvocation invoction, String resultCode) {// system.out.println ( "결과가 표시되기 전"); //}); System.out.println ( "인터셉트 demo2 이전"); 문자열 rtvalue = invocation.invoke (); // release system.out.println ( "intercepted demo2"); rtvalue를 반환하십시오. }}비. struts.xml에서 정의하고 인터셉터를 정의하고 사용하기 전에 먼저 정의해야합니다.
<package name = "p1"extends = "struts-default"> <!-정의 인터셉터 : 현재 패키지에만 유효합니다-> <interceptor name = "interceprotdemo1"> </interceptor> <interceptor name = "interceprotdemo2"> </interceptor> </interceptor>
기음. 행동 구성에 사용할 수 있습니다
<action name = "action1"method = "execute"> <!- 정의 된 인터셉터를 사용하십시오. 인터셉터가 지정되지 않은 경우 기본 스택 스택의 모든 인터셉터는 기본적으로 사용됩니다. 인터셉터가 지정되면 기본값은 유효하지 않습니다-> <interceptor-Ref name = "interceprotdemo1"> </interceptor-ref> <interceptor-ref name = "interceprotdemo2"> </interceptor-ref> <atured> /success.jsp </action>
조치 클래스 demo1Action을 구현하십시오
package com.ithema.action; import com.opensymphony.xwork2.actionSupport; public class demo1Action actionSupport {@override public string execute () rows exception {System.out.println ( "Execute Execute"); 반환 성공; }}실행 결과
파일 업로드, 데이터 검증, 요청 매개 변수를 struts2에서 acapsulating 요청 매개 변수와 같은 함수는 시스템의 기본 기본 스택에서 인터셉터에 의해 구현되므로, 우리가 정의하는 인터셉터는 시스템의 기본 기본 스타크를 참조해야하므로 응용 프로그램이 struts2 프레임 워크에서 제공하는 많은 기능을 사용할 수 있습니다.
인터셉터가 지정되지 않은 경우 기본 스택 스택의 모든 인터셉터는 기본적으로 사용됩니다. 인터셉터가 지정되면 기본값이 유효하지 않습니다. 사용자 정의 인터셉터를 사용하는 것 외에도 DefaultStack을 사용해야합니다. 당신은 이것을 할 수 있습니다
방법 1 : (직접 사용), 사용자 정의 및 기본 스타크를 작동 시키십시오.
방법 2 : (모든 사람이 사용하는 경우) 패키지 아래의 모든 동작이 사용자 정의 인터셉터를 사용하기를 원한다면 인터셉터 스택 인터셉터 스택을 사용하고 인터셉터 스택을 정의 한 다음 동작에서 <default-interceptor-ref name = "mydefaultstack"/>를 통해 인터셉터를 기본 인터셉터로 정의 할 수 있습니다.
<Interceptors> <interceptor name = "interceprotdemo1"> </interceptor> <interceptor name = "interceprotdemo2"> </interceprotdemo2 "> </interceptor> <interceptor-stack name ="myDefaultStack "> <interceptor-ref name ="defaultStack "> </interceptor-ref> <interceptor-ref> name = "InterceProtdemo1"> </interceptor-ref> <interceptor-Ref name = "InterceProtdemo2"> </interceptor-ref> </interceptor-stack> </interceptors> <action3 "방법 ="login "> <interceptor-Ref name ="myDefaultStack "> interceptor-ref> <결과> /success.jsp </result> </action>
3. Struts2의 자체 인터셉터
사례 1 : 사용자가 로그인되었는지 확인하십시오
1. 페이지 로그인을 쓰십시오 .jsp
<body> <form action = "$ {pagecontext.request.contextpath} /login.action"method = "post"> <input type = "text"name = "username"/> <br/> <입력 유형 = "텍스트"이름 = "input type ="value = "value ="login ".2. 로그인 확인을 위해 LoginCheckinterceptor 클래스를 작성하십시오
package com.ithema.interceptor; import javax.servlet.http.httpsession; import org.apache.struts2.servletactionContext; import com.opensymphony.xwork2.actionInvocation; import com.opensymphony.xwork.xpractor.aBsractor.AbstractInterceptor (public intercector extends intercector excector intercector) 호출)은 예외 {httpsession session = servletactionContext.getRequest (). getSession (); // sectletactionContext 객체 user user = session.getAttribute ( "user")를 통해 세션 객체를 가져옵니다. if (user == null) {// 로그인 없음 "로그인"; // 논리적보기로 돌아 가기} return invoction.invoke (); // release}}3. 구성 파일 쓰기 struts.xml
<package name = "p2"extends = "struts-default"> <interceptors> <interceptor> <interceptor name = "logincheckeckinterceptor"> </interceptor> <interceptor-stack name = "myDefaultStack"> <Interceptor-Ref name = "defaultStack"> </interceptor-ref> <interceptor-Ref name = goginCheck "> </interceptor-ref> </interceptor-stack> </interceptor-stack> </interceptors> <action name = "login"method = "login"> <culd> /login.jsp </result> </action> </package>
4. 액션 클래스 고객 행동을 작성하십시오
package com.itheima.action; import org.apache.struts2.servletactionContext; import com.opensymphony.xwork2.actionSupport; public class customerAction 확장 actionSupport {public String login () {System.out.println ( "login"); servletactionContext.getRequest (). getSession (). setAttribute ( "user", "ppp"); 반환 성공; }}사례 2 : 동작 방법의 실행 효율 모니터링
TimerInterceptor를 작성하십시오
package com.isheima.interceptor; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbStract -TimerInterceptor 확장 atbactingInterceptor {public string intercept (ActionInvocation invocation) {long time = system.nanoTime (); 문자열 rtvalue = invocation.invoke (); System.out.println (rtvalue+"실행 시간 :"+(System.NanoTime ()-시간)+"Nanosecond"); rtvalue를 반환하십시오. }}구성 파일을 작성하십시오
<package name = "p2"extends = "struts-default"> <interceptors> <interceptor> <interceptor name = "loginCheckeCepinterceptor"> </interceptor> <interceptor name = "TimerInterceptor"> </interceptor> <interceptor-stack name = "myDefaultStack"> <Interceptor-Ref Name = "interceptor-ref". 이름 = "LoginCheckinterceptor"> </interceptor-Ref> <Interceptor-Ref Name = "LoginCheckeCinterceptor"> </interceptor-ref> <interceptor-ref name = "TimerInterceptor"> </interceptor-ref> </intercepor-stack> </interceptors> <romect> </action> </rection> </rection>.
위에서 볼 수 있듯이 여러 필터는 한 가지 동작으로 구성 할 수 있습니다.
4. 사용자 정의 인터셉터 : 가로 채기 방법 또는 가로 채기하지 않는 방법을 지정할 수 있습니다.
가로 채는 방법이나 가로 채기없이 방법을 지정할 수 있습니다. 필터를 작성할 때는 두 개의 필드가있는 MethodFilterInterceptor 클래스를 구현할 수 있습니다. 매개 변수를 주입하여 가로 채지 않고 지정할 수 있습니다. 두 매개 변수 중 하나만 사용할 수 있습니다. 인터셉트가 적을 때는 includeMethods를 사용할 수 있습니다. 더 많은 인터셉트가 있으면 배제 방법을 사용할 수 있습니다.
excludemethods = collections.emptyset (); // 제외
IncludEmethods = collections.emptyset (); // 포함
사례 : 로그인 확인 예제를 계속하십시오.
1. 필터 로그 린 체크 린치 수용자를 작성하십시오
패키지 com.ithema.interceptor; import javax.servlet.http.httpsession; import org.apache.struts2.servletactionContext; import com.opensymphony.xwork2.actionInvocation; import com.opensymphony.xworks.Interceptor.AbstractInterceptor import com.opensymphony.xwork.xwork.xwork com.opensymphony.xwork2.interceptor.methodfilterinterceptor; public class logincheckinterceptor extends methodfilterinterceptor {protected string dointercept (actionInvocation vociation) Exception {httpsession session = servleTactionContext.getRequest (). Object User = session.getAttribute ( "사용자"); if (user == null) {// 로그인 없음 "로그인"; // 논리적보기로 돌아 가기} return invoction.invoke (); // release}}2. 구성 파일 쓰기
3. 액션 클래스 고객 행동을 작성하십시오
package com.itheima.action; import org.apache.struts2.servletactioncontext; import com.opensymphony.xwork2.actionSupport; public class customerAction 확장 actionSupport {public string add () {System.out.println ( "Call Add ()"; return string edit () {System.out.out. 성공;} public string login () {system.out.println ( "로그인"). 4. 페이지를 작성하십시오
AddCustomer.jsp
<바디> 고객 추가 </body>
editcustomer.jsp
<body> 고객 수정 </body>
login.jsp
<body> <form action = "$ {pagecontext.request.contextpath} /login.action"method = "post"> <input type = "text"name = "username"/> <br/> <입력 유형 = "텍스트"이름 = "input type ="value = "value ="login ".성공 .JSP
<body> oyeah </body>
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.