自定义注解+Spring 拦截器实现切面功能

本文详细介绍了一种基于自定义注解的权限验证方法,包括注解定义、拦截器实现及SpringMVC配置,展示了如何在Controller中使用注解进行权限控制,并提供了测试流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.自定义一个注解 权限判断用

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

/**
 * @author <a href="wangjianqiang@chaoxing.com">wangjianqiang</a>
 * @version 2019/3/8
 */
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface UserPermission {

	String value() default "student";
}

2.新建一个拦截器类

package interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import model.UserPermission;

/**
 * @author <a href="wangjianqiang@chaoxing.com">wangjianqiang</a>
 * @version 2019/3/8
 */
@Component
public class UserAuthInterceptor extends HandlerInterceptorAdapter {
     //前置
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		super.preHandle(request, response, handler);
		if (handler instanceof HandlerMethod) {
		 //获取方法处理器实例
			HandlerMethod myHandlerMethod = (HandlerMethod) handler;
			//得到当前方法
			Method method = myHandlerMethod.getMethod();
			//判断当前方法是否有UserPermission注解
			if (method.isAnnotationPresent(UserPermission.class)) {
			//获取UserPermission实例
				UserPermission userPermission = method.getAnnotation(UserPermission.class);
				if (userPermission != null) {
					// 有userPermission注解 执行相应逻辑
					if ("student".equals(userPermission.value())) {
						// 无权限
						System.out.println("preHandle 无权限!");
						response.sendRedirect("/hello/noperssion");

					} else {
						// 有权限
						System.out.println("preHandle 有权限!");
						return true;
					}
				}
			}
		}

		return true;
	}
    //后置方法
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
		System.out.println("postHandle back!");
	}
  
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
		System.out.println("afterCompletion zhixing!");
	}

}

3.在Spring MVC配置文件中定义拦截器

 <!--拦截器定义-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>  //拦截所有请求
            <bean class="interceptor.UserAuthInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

4.新建一个Controller测试

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import model.UserPermission;

/**
 * @author <a href="wangjianqiang@chaoxing.com">wangjianqiang</a>
 * @version 2019/3/8
 */
@Controller
@RequestMapping("/login")
public class LoginController {

	// 返回页面
	@RequestMapping(value = "/teacher", method = RequestMethod.GET)
	@UserPermission("teacher")    //传参  teacher
	public String login2() {
		System.out.println("通过权限");
		return "hello";
	}

	@RequestMapping(value = "/student", method = RequestMethod.GET)
	@UserPermission() //不传  默认student
	public String login3() {
		return "hello";
	}

}

5.
浏览器访问测试

(1)有权限
在这里插入图片描述
(2)无权限的 (重定向到 /hello/noperssion)

在这里插入图片描述

无权限时可在 preHandle方法拦截到时进行相应操作,例如重定向到登录页面,返回提示或错误信息 实现切面功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值