Implementing dynamic menu for Spring MVC/AOP application

安稳与你 提交于 2019-12-05 13:19:02

InterceptorDemo:

@Aspect
@Component
public class InterceptorDemo {

  @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
  public void requestMapping() {
  }
  @Pointcut("@annotation(you.package.RequestMenuMapping)")
  public void requestMenuMapping() {
  }


  @AfterReturning("requestMapping() && equestMenuMapping()")
  public void checkServer(JoinPoint joinPoint,Object returnObj) throws Throwable {
      Object[] args = joinPoint.getArgs();
      Model m = (Model)args[0];
      // use joinPoint get class or methd...
  }
}

If you want to intercept Contoller with you own, you can wirte another pointcut and ProceedingJoinPoint object can get what you want.

I think a better soultion would be a bean post processor to scan all controller classes for the @RequestMenuMapping and a HandlerInterceptor to add the menu items to every model map.

Q1: ModelAndView object create at org.springframework.web.servlet.DispatcherServlet.doDispatch()

// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

// Do we need view name translation?
if (mv != null && !mv.hasView()) {
    mv.setViewName(getDefaultViewName(request));
}

So, you can intercept handle method after returing or override the method.

Q2:As far as i know, there are two ways getting annotation methods.

1.Use AOP: You can declare a pointcut like this:

@Pointcut("@annotation(you.package.RequestMenuMapping)")
public void requestMenuMappingPountcut() {
}

2.Use reflection.

Class clazz = Class.forName(classStr);
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
    if (method.isAnnotationPresent(RequestMapping.class)
            && method.isAnnotationPresent(RequestMenuMapping.class)) {
        // do something
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!