拦截器:
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