Struts2中可以使用自定义拦截器,实现登录及权限控制功能。
具体看下面的步骤:
1. 自定义拦截器类, 类 继承 AbstractInterceptor类
public class AuthorityInterceptor extends AbstractInterceptor { public String intercept(ActionInvocation invocation) throws Exception { ActionContext ctx = invocation.getInvocationContext(); User mu = (User) ctx.getSession().get("USER"); //登录控制 if (mu != null && mu.getUserName() != null) { String actionName = invocation.getInvocationContext().getName(); //权限控制代码写这里 return invocation.invoke(); } else { return "loginError"; } } }
2. 编写struts.xml
<package name="all" extends="struts-default">
<!-- 配置拦截器 -->
<interceptors>
<interceptor name="authority" class="com.myinterceptor.AuthorityInterceptor" />
<interceptor-stack name="mydefault">
<interceptor-ref name="defaultStack" />
<interceptor-ref name="authority" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="mydefault" />
<!-- <default-action-ref name="loginMasUser" /> -->
<!-- 配置全局跳转界面 -->
<global-results>
<result name="loginError" type="redirect">login.jsp</result>
<result name="error">error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="error" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
</package>
3 . 让项目模块实现拦截器
其他模块新建struts配置文件,并继承配置有拦截器的包,访问dept模块时就会进入拦截器进行拦截,例: struts-dept.xml,
<package name="dept" namespace="/" extends="all">
<!-- 配置操纵 dept 的action-->
</package>
其他模块按照dept模块进行配置就可以了
就这样,客户端每次发送请求到action时就会进行拦截了。
需要注意的:登录与登出action不要配置到拦截器里