public class UserInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { // 得到当前执行的方法 String methodName = invocation.getProxy().getMethod(); // 得到ActionContext对象 ActionContext ac = invocation.getInvocationContext(); // 获取session, 从session中获取登陆的管理员账号 Object obj = ac.getSession().get("adminInfo"); // 判断: if (!"login".equals(methodName) && !"list".equals(methodName)){ // 验证 if (obj == null){ // 没有登陆 return "login"; } else { // 执行Action return invocation.invoke(); } } else { // 允许访问登陆、列表展示 return invocation.invoke(); } }}
<!-- 拦截器配置 --> <interceptors> <interceptor name="userInterceptor" class="cn.itcast.action.UserInterceptor"></interceptor> <interceptor-stack name="myStack"> <interceptor-ref name="defaultStack"></interceptor-ref> <interceptor-ref name="userInterceptor"></interceptor-ref> </interceptor-stack> </interceptors> <!-- 执行指定的拦截器 --> <default-interceptor-ref name="myStack"></default-interceptor-ref>