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

前端 未结 2 1664
别跟我提以往
别跟我提以往 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:40

    A controller advice can be limited to certain controllers (not methods) by using one of the values of the @ControllerAdvice annotation, e.g.

    @ControllerAdvice(assignableTypes = {MyController1.class, MyController2.class})
    

    If you need to do it on a method level I suggest to take a look at Interceptors.

    0 讨论(0)
  • 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. :)

    0 讨论(0)
提交回复
热议问题