Struts2-权限拦截器
1、写一个权限监听类
import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import java.util.*; public class UserLoginInterceptor extends AbstractInterceptor { public String tip; public String getTip() { return tip; } public void setTip(String tip) { this.tip = tip; } public String intercept(ActionInvocation invocation) throws Exception { ActionContext ctx = invocation.getInvocationContext(); Map session = ctx.getSession(); User user =(User)session.get("User"); if (user != null) { return invocation.invoke(); }else{ ctx.put("tip" , "请登录!"); setTip("请登录!"); //return Action.LOGIN; return "userLogin"; } } }
第二步,写个struts2的配置文件,也就所谓的xml
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 定义含“权限检查拦截器”的包,供其他模块引用 --> <package name="struts-default-with-auth-check" extends="struts-default" > <interceptors> <!-- 定义“权限检查拦截器” --> <interceptor name="userCheck" class="com.interceptor.UserLoginInterceptor"> </interceptor> <!-- 定义含“权限检查拦截器”的拦截器栈,注意缺省的拦截器栈“defaultStack”要放在前面 --> <interceptor-stack name="userStack"> <!-- <interceptor-ref name="defaultStack" /> --> <interceptor-ref name="userCheck"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 正式应用可能含很多package,为了能从其他package中跳转到登录页面,把登录页面定义成全局result <default-interceptor-ref name="userStack"></default-interceptor-ref> --> <global-results> <result name="userLogin">login.jsp</result> <result name="adminLogin">login.jsp</result> </global-results> </package> </struts>
第三步
其他的xml都继承这个xml
然后再xml的action中加入
<interceptor-stack name="userStack"/>
就OK了