相关阅读:
Spring Boot+JPA微服务中数据更新问题(update)
Spring Boot集成X-admin2.2时,Layui字体图标无法正常显示或乱码问题解决方法
ZTree工具类汇总,包括:新增、编辑和删除节点,并提交后台
如何在Spring Boot的拦截器中对前端操作按钮进行控制?如何通过拦截器中handler对象, 获取访问的方法和类的注解信息?
拦截器代码如下:
package com.tdata.bplatform.web.interceptor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.tdata.bplatform.modules.entity.User;
import com.tdata.bplatform.utils.String.StringUtils;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* 基础拦截器 - 向 request 中添加一些基础变量
*
* @author YingFan
*
*/
@Component
public class BaseInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
request.setAttribute("base", request.getContextPath());
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
super.afterCompletion(request, response, handler, ex);
}
@Override
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
super.afterConcurrentHandlingStarted(request, response, handler);
}
}
如果想要获取方法和类的注解值,需要在“preHandle”方法中进行处理,具体获取方法如下所示:
获取类注解
String classAnnotationValue = "";
// 获取当前方法的类;
Class<?> clazz = handlerMethod.getMethod().getDeclaringClass();
// 获取类注解;
RequestMapping classAnnotation = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
if (classAnnotation != null) {
if (classAnnotation.value().length > 0) {
classAnnotationValue = classAnnotation.value()[0].toString();
}
}
获取方法注解
String methodAnnotationValue = "";
// 获取当前访问的方法
Method method = handlerMethod.getMethod();
// 获取方法注解
RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
if (methodAnnotation != null) {
if (methodAnnotation.value().length > 0) {
methodAnnotationValue = methodAnnotation.value()[0].toString();
}
}
System.out.println("类注解:" + classAnnotationValue + " 方法注解:" + methodAnnotationValue);