Struts2的拦截器只允许有权限用户访问action

1、定义拦截器,继承MethodFilterInterceptor 

package com.life.stuts.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

/**
 * 如果不是login的adction,使用自定义拦截器判断用户是否为空。为空,跳转到登陆页面;否则,继续执行。
 * 在配置拦截器属性excludeMethods、includeMethods进行方法过滤时发现不起作用。
 * 要想使方法过滤配置起作用,拦截器需要继承MethodFilterInterceptor类。
 * MethodFilterInterceptor类是AbstractInterceptor的子类
 * @author JL
 * 
 */

public class SellerInterceptor extends MethodFilterInterceptor {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        Map<String, Object> sessionValues = invocation.getInvocationContext()
                .getSession();
        String seller = (String) sessionValues.get("seller");
        // 如果没有管理员登陆或商家登陆,就返回到登陆页面,否则继续访问原action
        System.out.println("action拦截器");
        if (seller == null) {
            return "loginscript";
        }
        return invocation.invoke();
    }

}

2、struts.xml的配置,希望对那个action进行拦截就把interceptor 放里面,要加上defaultStack。

        <interceptors>
            <interceptor name="authentication"
                class="com.life.stuts.interceptor.AuthenticationInterceptor"></interceptor>
        </interceptors>
<global-results>
            <result name="login">/</result>
        </global-results>
<action name="*_manage" method="{1}" class="ManageAction">
            <!-- param是K-V形式,在action的类文件中调用,前提是类中有这样一个变量,并且提供get-set方法 -->
            <interceptor-ref name="authentication"></interceptor-ref>
            <!-- 在配置了其它拦截器之后,必须加上defaultStack,否则jsp无法向action传值 ,且文件上传也失效 -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
        </action>

 3、实现对action的某些方法不拦截

excludeMethods表示不进行拦截

includeMethods表示要拦截

<interceptor-ref name="sellerauthentication">
                <param name="includeMethods"></param>
                <param name="excludeMethods">login,logout</param>
            </interceptor-ref>

Done

原文地址:https://www.cnblogs.com/xingyyy/p/3896831.html