1 Struts2的方法拦截器
1.1 拦截器
- 拦截器继承MethodFilterInterceptor,具有拦截struts2的action方法调用的能力
- 下面是拦截用户是否登录,需要在登录的时候存入登录用户到session中,然后判断session是否含有该用户
/**
* 权限拦截器
*/
public class PrivilegeInterceptor extends MethodFilterInterceptor
{
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception
{
User user=(User)ActionContext.getContext().getSession().get("existUser");
if(user!=null){
// 已经登录
return invocation.invoke();
}else {
ActionSupport actionSupport=(ActionSupport) invocation.getAction();
actionSupport.addActionError("还没有登录,没有权限访问!");
return "login";
}
}
}
1.2 拦截器的配置
1.2.1 配置拦截器
<interceptors>
<interceptor name="privilegeInterceptor" class="com.zgd.learn.crm.web.interceptor.PrivilegeInterceptor"></interceptor>
</interceptors>
1.2.2 设置全局result,result需要放在interceptor后面
<!-- 因为需要在各个拦截的地方跳转到登录界面,所以需要配置全局的result -->
<global-results>
<result name="login">/login.jsp</result>
</global-results>
1.2.3 在每个需要拦截的action中配置拦截器
* 需要添加默认拦截器
* 在用户登录和注册的时候,不应该使用拦截器,需要排除该方法
* 其他需要使用权限拦截器的添加该拦截器
<interceptor-ref name="privilegeInterceptor">
<!-- 权限拦截器不能拦截登录和注册功能 -->
<param name="excludeMethods">regist,login</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
1.3 示例配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 配置Struts2的常量 -->
<constant name="struts.action.extension" value="action"/>
<package name="crm" extends="struts-default" namespace="/">
<!-- 权限拦截器 -->
<interceptors>
<interceptor name="privilegeInterceptor" class="com.zgd.learn.crm.web.interceptor.PrivilegeInterceptor"></interceptor>
</interceptors>
<!-- 因为需要在各个拦截的地方跳转到登录界面,所以需要配置全局的result -->
<global-results>
<result name="login">/login.jsp</result>
</global-results>
<action name="user_*" class="userAction" method="{1}">
<result name="login">/login.jsp</result>
<result name="success">/index.jsp</result>
<interceptor-ref name="privilegeInterceptor">
<!-- 权限拦截器不能拦截登录和注册功能 -->
<param name="excludeMethods">regist,login</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
<action name="baseDict_*" class="baseDictAction" method="{1}">
</action>
<action name="saleVisit_*" class="saleVisitAction" method="{1}">
<result name="findAll">/jsp/salevisit/list.jsp</result>
<result name="saveUI">/jsp/salevisit/add.jsp</result>
<result name="saveSuccess" type="redirectAction">saleVisit_findAll.action</result>
<!-- 引用拦截器 -->
<interceptor-ref name="privilegeInterceptor"/>
<interceptor-ref name="defaultStack"/>
</action>
</package>
</struts>