攔截器:
package cn.itcast.interceptor;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/** * 權限攔截 (攔截是否登陸) * * @author seawind * */
public class PrivilegeInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation invocation) throws Exception {
// 判斷用戶是否登陸
if (ServletActionContext.getRequest().getSession() .getAttribute("loginUser") == null) {
// 未登陸
return "login";
} else {
// 已經登陸
return invocation.invoke();
}
}
}
struts里面的配置如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts SYSTEM "http://struts.apache.org/dtds/struts-2.3.dtd" PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"> -<struts>
<constant value="true" name="struts.devMode"/>
<constant value="messages" name="struts.custom.i18n.resources"/>-
<package name="basic" extends="struts-default" namespace="/">
//自定義的攔截器,要配置到需要使用的包里面
<!-- 注冊攔截器 --> -
<interceptors><interceptor name="privilege" class="cn.itcast.interceptor.PrivilegeInterceptor"/>
<!-- 自定義攔截器棧 --> -
<interceptor-stack name="privilegeStack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="privilege"/>
</interceptor-stack>
</interceptors>
<!-- 設置當前包 所有Action 都使用 自定義攔截器棧 -->
<default-interceptor-ref name="privilegeStack"/>-
<global-results>
<result name="login">/login.jsp</result>
</global-results>
<!-- 圖書管理 -->
-<action name="book_*" class="cn.itcast.action.BookAction" method="{1}">
//下面這種配置方式也可以,但比較麻煩,注釋掉了。
<!-- 使用攔截器 -->
<!-- 當使用自定義攔截器 后,默認攔截器 就會失效 -->
<!-- <interceptor-ref name="defaultStack"></interceptor-ref> -->
<!-- <interceptor-ref name="privilege"></interceptor-ref> -->
</action>
</package>-
<package name="login" extends="struts-default" namespace="/">
<!-- 登陸 -->
-<action name="login" class="cn.itcast.action.LoginAction">
<result name="input">/login.jsp</result><result>/index.jsp</result>
</action></package>
</struts
