`
Peerless_
  • 浏览: 4100 次
  • 性别: Icon_minigender_1
社区版块
存档分类
最新评论

公共數據權限過濾 (使用 structs 拦截器)

    博客分类:
  • java
阅读更多
1.先定义一个注解
package com.efoxconn.ipebg.protoline.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataAuth {
	public String[] types() default {"project", "site"};
}


2.创建拦截器
package com.efoxconn.ipebg.protoline.interceptor;

import java.lang.reflect.Method;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.efoxconn.ipebg.protoline.annotation.DataAuth;
import com.efoxconn.ipebg.protoline.util.CheckDataUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
@Component
@SuppressWarnings("unchecked")
public class DataAuthInterceptor extends AbstractInterceptor {

	/**
	 * 公共數據權限過濾
	 */
	private static final long serialVersionUID = -4013438146040038934L;
	@Autowired
	CheckDataUtil checkDataUtil;
	
	private String transName(String name){
		return name+"_id";
	}
	
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String methodName=invocation.getProxy().getMethod();
		Class<?> clazz=invocation.getAction().getClass();
		Method method=clazz.getMethod(methodName);
		DataAuth dataAuth = null;
		
		if(clazz.isAnnotationPresent(DataAuth.class)){
			dataAuth=clazz.getAnnotation(DataAuth.class);
		}else if (method.isAnnotationPresent(DataAuth.class)) {
			dataAuth=method.getAnnotation(DataAuth.class);
		}
		if (dataAuth!=null) {
			Method getMethod=clazz.getMethod("getParams");
			Method setMethod=clazz.getMethod("setParams", Map.class);
			Map params = (Map) getMethod.invoke(invocation.getAction());
			String[] types = dataAuth.types();
			for(String type : types){
				String name = transName(type);
				if(params.containsKey(name)){
					params.put(name, checkDataUtil.checkAuth((String) params.get(name), "auth_"+type));
				}
			}
			setMethod.invoke(invocation.getAction(), params);
		}
		return invocation.invoke();	
	}

}


3. 配置拦截器
在struts的配置文件里
<interceptors>
			<interceptor name="dataAuth" class="dataAuthInterceptor"/>
			<interceptor-stack name="dataAuthStack" >
				<interceptor-ref name="actionStack"/>
				<interceptor-ref name="dataAuth"/>
			</interceptor-stack>
</interceptors>
<default-interceptor-ref name="dataAuthStack"/>

4. 在需要使用的类或方法上加上注解就好了
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics