編寫攔截器的兩種方法:
1、繼承AbstractInterceptor類,重寫intercept方法()這裡對攔截到的内容進行處理
/**
* 登入攔截器
*/
package com.abc.hotel.interceptor;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.abc.hotelsys.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @author 别說難忘記
*
*/
public class LoginInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String path = ServletActionContext.getRequest().getRequestURI();
if(path.contains("getImageCode")||path.contains("checkLogin")||path.contains("toLogin")) {
return invocation.invoke();
}
ActionContext actionContext = ActionContext.getContext();
Map<String, Object> session = actionContext.getSession();
User user = (User) session.get("loginUser");
if(user!=null) {
return invocation.invoke();
}else {
System.out.println("未登入,進行攔截!"+path);
return "login_page";
}
}
}
2、實作Interceptor接口
/**
* 登入攔截器
*/
package com.abc.hotel.interceptor;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.abc.hotelsys.domain.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* @author 别說難忘記
*
*/
public class LoginInterceptor implements Interceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String path = ServletActionContext.getRequest().getRequestURI();
if(path.contains("getImageCode")||path.contains("checkLogin")||path.contains("toLogin")) {
return invocation.invoke();
}
ActionContext actionContext = ActionContext.getContext();
Map<String, Object> session = actionContext.getSession();
User user = (User) session.get("loginUser");
if(user!=null) {
return invocation.invoke();
}else {
System.out.println("未登入,進行攔截!"+path);
return "login_page";
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
}
對Struts配置檔案進行配置攔截器
struts.xml
<package name="hotelsysPkg" abstract="true" extends="struts-default" >
<interceptors >
<interceptor name="loginValidate" class="com.abc.hotel.interceptor.LoginInterceptor" />
<interceptor-stack name="mystack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="loginValidate"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="mystack" />
<global-results>
<result name="login_page">../WEB-INF/views/login.jsp</result>
</global-results>
</package>
運作截圖如下: