拦截器的使用步骤:
1、创建一个类,实现Interceptro接口,并其中的intercept方法。
2、在配置文件中通过<interceptors></interceptors>声明拦截器。
3、通过<interceptor-ref>引用拦截器。
一下为用拦截器实现简单的权限控制:
Action:
public class InterceptorAction extends ActionSupport{ public String saveUser(){ System.out.println("Save User"); return "privilege"; } }Interceptor:
public class PrivilegeInterceptor implements Interceptor{ @Override public void destroy() { // TODO Auto-generated method stub } @Override public void init() { // TODO Auto-generated method stub } @Override public String intercept(ActionInvocation invocation) throws Exception { String username = ServletActionContext.getRequest().getParameter("username"); if("admin".equals(username)){ invocation.invoke(); return "privilege"; }else{ ActionContext.getContext().put("message", "权限不足,无法添加用户!"); return "privilege"; } } }配置文件:
<interceptors> <!-- 声明拦截器 --> <interceptor name="privilegeInterceptor" class="cn.itcast.interceptor.PrivilegeInterceptor"></interceptor> <!-- 声明拦截器栈 --> <interceptor-stack name="privilegeStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <!-- 引用拦截器 --> <interceptor-ref name="privilegeInterceptor"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 通过拦截器栈使用拦截器 --> <default-interceptor-ref name="privilegeStack"></default-interceptor-ref> <action name="interceptor_*" method="{1}" class="cn.itcast.inteceptorAction.InterceptorAction"> <result name="privilege">interceptor.jsp</result> </action>interceptor.jsp:
<s:form action="interceptor_saveUser.action"> <s:textfield name="username"></s:textfield> <s:submit></s:submit> </s:form> <s:if test="#message!=null"> <s:property value="#message"/> </s:if>拦截器的意义:可以把一些和业务逻辑没有关系的代码放到拦截器中,做到这些代码和业务逻辑的松耦合。
拦截器的执行顺序:按拦截器在拦截器栈中定义的顺序,从上往下执行。