此篇是實作上篇所說明的程式碼
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<package name="user" namespace="/User" extends="struts-default">
<!-- 攔截器 -->
<interceptors>
<!-- (單一)宣告自定義攔截器 -->
<interceptor name="MyInterceptor" class="com.brian.example.interceptor.MyInterceptor"></interceptor>
<!-- (組合)定義其他攔截器,可引用其他攔截器 -->
<interceptor-stack name="defaultInterceptorStack">
<interceptor-ref name="MyInterceptor"></interceptor-ref>
<interceptor-ref name="i18n"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
<!-- (組合)定義其他攔截器,可引用其他攔截器 -->
<interceptor-stack name="defaultInterceptorStack111">
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 以下功能是針對 "全部" action ,所以只要經過 struts.xml 就一定會先經過他-->
<!-- 如果有部分頁面或功能不需要到,就不要使用此功能 -->
<default-interceptor-ref name="MyInterceptor"></default-interceptor-ref>
<!-- 全部對應 result 頁面 -->
<global-results>
<result name="block">/WEB-INF/jsp/block.jsp</result>
</global-results>
<action name="hello" class="com.brian.example.action.HelloAction"
method="execute">
<result name="success">/WEB-INF/jsp/hello.jsp</result>
</action>
<action name="data" class="com.brian.example.action.DataAction"
method="execute">
<interceptor-ref name="MyInterceptor"/>
<result name="success">/WEB-INF/jsp/data.jsp</result>
</action>
</package>
</struts>
以下是自定義攔截器
package com.brian.example.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor implements Interceptor {
private static final long serialVersionUID = 1L;
@Override
public void destroy() {
System.out.println("-----攔截器銷毀-----");
}
@Override
public void init() {
System.out.println("-----攔截器生成-----");
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("---------攔截器---------");
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
HttpSession session = request.getSession();
// 判斷某事件,例如:Token. Record 記錄是否存在
if (session.getAttribute("token")!= null) {
// 建議
System.out.println("Hello" + session.getAttribute("token"));
// 如果存在,直接略過此攔截
return invocation.invoke();
} else {
// 如果不存在,則導至某頁面
return "block";
}
}
}
歡迎轉載,請註明出處。
沒有留言:
張貼留言