一,註解類
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);
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";
}