SpringAOP实现用户权限验证
每个项目都会有权限管理系统
无论你是一个简单的企业站,还是一个复杂到爆的平台级项目,都会涉及到用户登录、权限管理这些必不可少的业务逻辑。有人说,企业站需要什么权限管理阿?那行吧,你那可能叫静态页面,就算这样,但你肯定也会有后台管理及登录功能。
每个项目中都会有这些几乎一样的业务逻辑,我们能不能把他们做成通用的系统呢?
AOP实现用户权限验证
在从零开始学Java-SpringAOP拦截器的基本实现这篇文章中,我详细的写了什么是AOP?、AOP主要能实现什么功能?
AOP在实际项目中运用的场景主要有权限管理(AuthorityManagement)、事务管理(TransactionManagement)、安全管理(Security)、日志管理(Logging)和调试管理(Debugging)等。
所以,权限验证正好我们可以使用AOP来直接实现。具体你项目中权限怎么管理,管理的粒度是什么级别这些完全取决于项目需要,这里完全不做任何的讨论。
先说思路:利用自定义注解及拦截器来在你需要的时候,进行你需要的一些权限认证。这里依然涉及到的有enum(枚举)、annotation(自定义注解)及拦截器相关知识,废话不多说,直接开写代码。
开始撸一下代码
一、建立AuthorityType.java枚举类
publicenumAuthorityType{
//登录和权限都验证默认
Validate,
//不验证
NoValidate,
//不验证权限
NoAuthority;
}
这个枚举类的作用,依然是使自定义注解用起来爽到还想要。
二、新建Authority.java自定义注解类
importjava.lang.annotation.Documented;
importjava.lang.annotation.ElementType;
importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public@interfaceAuthority{
//默认验证
AuthorityTypevalue()defaultAuthorityType.Validate;
}
三、再建一个AuthorityAnnotationInterceptor.java类
/
权限认证拦截器
/
publicclassAuthorityAnnotationInterceptorextendsHandlerInterceptorAdapter{
@Override
publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)
throwsException{
if(handlerinstanceofHandlerMethod){
HandlerMethodhm=(HandlerMethod)handler;
Class>clazz=hm.getBeanType();
Methodm=hm.getMethod();
try{
if(clazz!=null&&m!=null){
booleanisClzAnnotation=clazz.isAnnotationPresent(Authority.class);
booleanisMethondAnnotation=m.isAnnotationPresent(Authority.class);
Authorityauthority=null;
//如果方法和类声明中同时存在这个注解,那么方法中的会覆盖类中的设定。
if(isMethondAnnotation){
authority=m.getAnnotation(Authority.class);
}elseif(isClzAnnotation){
authority=clazz.getAnnotation(Authority.class);
}
intcode=-1;
Stringmsg="";
if(authority!=null){
if(AuthorityType.NoValidate==authority.value(www.hunanwang.net)){
//标记为不验证,放行
returntrue;
}elseif(AuthorityType.NoAuthority==authority.value(www.visa158.com)){
//不验证权限,验证是否登录
//TODO:
returntrue;
}else{
//验证登录及权限
//TODO:
code=1;
msg="验证成功!";
returntrue;
}
}
////跳转
//Stringurl="";
//response.getWriter().write("");
//returnfalse;
//未通过验证,返回提示json
MapresponseMap=newHashMap();
responseMap.put("code",code);
responseMap.put("msg",msg);
responseMap.put("params","");
responseMap.put("rows","");
Stringjson=newGson().toJson(responseMap);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
returnfalse;
}
}catch(Exceptione){
}
}
returnfalse;
}
}
这个类的目的就是在打过Authority标签的方法及类上,进行权限认证。我这里分了三种类型:全部验证、只验证登录、不验证用来满足我们的业务需求。
这里的返回值可以是JSON串,也可以是跳转到相应的页面,来实现你想要的效果。
四、配置拦截器
在/WebContent/WEB-INF/springMVC-servlet.xml文件下的节点配置就行,这里可以配置具体要拦截的Url。
到这里就完成了权限验证的工作了,如何使用呢?
使用就非常简单
因为我们的拦截器配置,然后我们在自定义注解的默认是验证,所以,我们只需要在类名及方法名上打标签就可以。
|
|