自定义注解+Struts2拦截器实现简单权限控制

自己用struts2的拦截器,配合注解写了个简单的权限控制。  

功能:判断某些action访问时必须用户登陆。


拦截器代码:

 
 
public class CheckPrivilegeInterceptor extends AbstractInterceptor {

	//过滤方法
	@Override
	public String intercept(ActionInvocation invocation) throws Exception 
	{

		// 判断用户是否登陆
		User user = (User) ActionContext.getContext().getSession().get("user"); // 当前登录用户
		String namespace = invocation.getProxy().getNamespace();
		String actionName = invocation.getProxy().getActionName();
		// 对应的权限URL
		String privUrl = namespace + actionName; 
		
		//获取请求的action对象  
        Object action=invocation.getAction();  
          
        //获取请求的方法的名称  
        String methodName=invocation.getProxy().getMethod();  
          
        //获取action中的方法的封装类(action中的方法没有参数)  
        Method method=action.getClass().getMethod(methodName, null);  
  
        //获取request对象  
        HttpServletRequest request=ServletActionContext.getRequest();  
        boolean isNeedLogin = CheckLoginAnnotation(request,method);
       
    	//如果登陆了
    	if(null==user)
    	{
    		//判断是否有需要登录的注解
   		 	if(isNeedLogin)
   		 	{
   		 		return "noLogin";
   		 	}
   		 	else
   		 	{
   		 		return invocation.invoke();
   		 	}
    		
    	}
    	else 
    	{
			if (user.hasPrivilegeByUrl(privUrl)) 
			{
				// 如果有权限,就放行
				return invocation.invoke();
			} else {
				// 如果没有权限,就转到提示页面
				return "noPrivilegeError";
			}
		}
		
	}
	
	/**
	 * 判断是否有需要登陆注解
	 * @param request
	 * @param method
	 * @return
	 */
	public boolean CheckLoginAnnotation(HttpServletRequest request, Method method) {  
        if(method==null){  
            return false;  
        }  
        //判断用户请求的method上面是否存在注解  
        boolean isAnnotationPresent= method.isAnnotationPresent(CheckLogin.class);  
        return isAnnotationPresent;
          
    }  

}

自定义注解:


@Retention(RetentionPolicy.RUNTIME)
public @interface CheckLogin {


}



你可能感兴趣的:(自定义注解+Struts2拦截器实现简单权限控制)