使用到spring方法拦截器 MethodInterceptor实现权限控制,MethodInterceptor可以使用通配符,并且是基于注解的。
简单例子代码如下:
1、定义需要拦截的类
Java代码 收藏代码
public class LoginAction{
//没有权限限制
@RequestMapping(value = "/login")
public void login(HttpServletRequest req, HttpServletResponse res) {
//登录功能.
}
//需要登录完成后才可访问
@LoginMethod
@RequestMapping(value = "/userList")
public void userList(HttpServletRequest req, HttpServletResponse res) {
//获取用户列表
}
}
注意上面的@LoginMethod是我自定义的注解
2、定义LoginMethod注解
Java代码 收藏代码
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginMethod {
}
3、定义MethodInterceptor拦截器
Java代码 收藏代码
public class SystemMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Method method = methodInvocation.getMethod();
if(method.isAnnotationPresent(LoginMethod.class)){//加了@LoginMethod注解,被拦截
User user = sessionUtil.getCurrUser();
if(user == null){//未登录
//proceed方法不调用,方法被拦截
return null;
}else{
return methodInvocation.proceed();//该方法不调用,则被拦截的方法不会被执行
}
}else{
return methodInvocation.proceed();
}
}
}
4、配置文
Xml代码 收藏代码
<bean id="systemMethodInterceptor" class="com.tzz.interceptor.SystemMethodInterceptor" >
</bean>
<aop:config>
<!--切入点-->
<aop:pointcut id="methodPoint" expression="execution(* com.tzz.controllor.web.*.*(..)) "/><!--在该切入点使用自定义拦截器-->
<aop:advisor pointcut-ref="methodPoint" advice-ref="systemMethodInterceptor"/>
</aop:config>
简单例子代码如下:
1、定义需要拦截的类
Java代码 收藏代码
public class LoginAction{
//没有权限限制
@RequestMapping(value = "/login")
public void login(HttpServletRequest req, HttpServletResponse res) {
//登录功能.
}
//需要登录完成后才可访问
@LoginMethod
@RequestMapping(value = "/userList")
public void userList(HttpServletRequest req, HttpServletResponse res) {
//获取用户列表
}
}
注意上面的@LoginMethod是我自定义的注解
2、定义LoginMethod注解
Java代码 收藏代码
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginMethod {
}
3、定义MethodInterceptor拦截器
Java代码 收藏代码
public class SystemMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
Method method = methodInvocation.getMethod();
if(method.isAnnotationPresent(LoginMethod.class)){//加了@LoginMethod注解,被拦截
User user = sessionUtil.getCurrUser();
if(user == null){//未登录
//proceed方法不调用,方法被拦截
return null;
}else{
return methodInvocation.proceed();//该方法不调用,则被拦截的方法不会被执行
}
}else{
return methodInvocation.proceed();
}
}
}
4、配置文
Xml代码 收藏代码
<bean id="systemMethodInterceptor" class="com.tzz.interceptor.SystemMethodInterceptor" >
</bean>
<aop:config>
<!--切入点-->
<aop:pointcut id="methodPoint" expression="execution(* com.tzz.controllor.web.*.*(..)) "/><!--在该切入点使用自定义拦截器-->
<aop:advisor pointcut-ref="methodPoint" advice-ref="systemMethodInterceptor"/>
</aop:config>