How to target specific handlers with a @ControllerAdvice @ModelAttribute?

前端 未结 2 1665
别跟我提以往
别跟我提以往 2021-01-15 15:31

I\'d like to display a warning message on specific pages 5 minutes prior to a system shutdown. Rather than add it manually to each these pages I created a @ControllerAdvice

2条回答
  •  一生所求
    2021-01-15 15:58

    Thanks to @zeroflagL for pointing me to the interceptor solution. I ditched the @ControllerAdvice approach and ended up with this:

    Custom annotation:

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Qualifier
    public @interface MaintAware {
        String name() default "MaintAware";
    }
    

    Interceptor:

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        MaintAware maintAware = method.getAnnotation(MaintAware.class);
        if (maintAware != null) {
            Locale locale = request.getLocale();
            if (isMaintenanceWindowSet() && !isMaintenanceInEffect()) {
                String msg = getImminentMaint(locale);
                if (!msg.isEmpty())
                    modelAndView.addObject("warningMaint", msg);
            }
        }
    
        super.postHandle(request, response, handler, modelAndView);
    }
    

    Now I can annotate the specific methods that require the maintenance notification. Easy peasy. :)

提交回复
热议问题