使用自定義註解做權限控制

一,註解類

package test.annotation;

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

/**
 * 註解類
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Authority {
	
	String value() default "";
}

二,切面控制類

package test.aspect;

import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.fastjson.JSONObject;
import test.annotation.Authority;

@Aspect
@Component
public class AuthorityAspect {
	
	@Around("@annotation(authority)")
	public Object permission(ProceedingJoinPoint pjp,Authority authority) throws Throwable {
		try {
			String key = authority.value();
			System.out.println(key);
			//HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			//HttpSession session = request.getSession();
			if(!"ok".equals(key)){
				throw new Exception("你沒有 " + key + " 的權限!");
			}
			return pjp.proceed();
		} catch (Exception e) {
			this.out(e.getMessage());
			return null;
		}
	}
	
    
    private void out(String msg) throws IOException {
       HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
       JSONObject obj = new JSONObject();
       obj.put("success", false);
       obj.put("message", msg);
       response.setContentType("text/x-json;charset=UTF-8");
       response.getWriter().print(obj);
    }
}

三,權限控制的使用

@Authority("ok")
@RequestMapping(value = "/test1", method = RequestMethod.GET)
public Object test1(){
    return "ok";
}

@Authority("ok1")
@RequestMapping(value = "/test2", method = RequestMethod.GET)
public Object test2(){
    return "ok";
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章