使用到spring方法拦截器 MethodInterceptor实现权限控制,MethodInterceptor可以使用通配符,并且是基于注解的。
简单例子代码如下:
1、定义需要拦截的类
- 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注解
- @Target(ElementType.METHOD) //方法
- @Retention(RetentionPolicy.RUNTIME) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
- public @interface LoginMethod {
-
- }
3、定义MethodInterceptor拦截器
- public class SystemMethodInterceptor implements MethodInterceptor {
- @Override
- public Object invoke(MethodInvocation methodInvocation) throws Throwable {
- Method method = methodInvocation.getMethod();
- if(method.isAnnotationPresent(LoginMethod.class)){
- User user = sessionUtil.getCurrUser();
- if(user == null){
-
- return null;
- }else{
- return methodInvocation.proceed();
- }
- }else{
- return methodInvocation.proceed();
- }
- }
- }
4、配置文
- <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>
spring方法拦截实例
原文:http://www.cnblogs.com/canghaihongxin/p/7102986.html