Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

spring mvc - How to target specific handlers with a @ControllerAdvice @ModelAttribute?

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 class with a @ModelAttribute method that adds the message to the Model parameter, but from what I understand reading the documentation and SO and some initial testing this model attribute will be added to every method with a @RequestMapping.

I realize I could refactor my code so that the targeted methods are all in one controller and limit the @ControllerAdvice to that one controller, but I would end up with a collection of otherwise non-related methods in that controller which muddies up the overall structure of my controllers.

So, is there a way to indicate which specific methods in multiple controllers the @ModelAttribute is applied to? Would a custom annotation be a solution (not sure how that would work)? I'd like to do this via annotations if possible.

Edit:

The @ControllerAdvice code is pretty basic:

@ControllerAdvice
public class GlobalModelController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MaintenanceInterceptor maintInterceptor; 

    @ModelAttribute()
    public void globalAttributes(Model model, Locale locale) {
        if (maintInterceptor.isMaintenanceWindowSet() && !maintInterceptor.isMaintenanceInEffect()) {
            String msg = maintInterceptor.getImminentMaint(locale);
            model.addAttribute("warningMaint", msg);
            logger.debug("maint msg= " + msg);          
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...