在没有RedirectAttributes的环境中如何在重定向环境中报错错误提示信息供页面使用

Spring在无RedirectAttributes的情况下(如Interceptor、filter中)使用Flash scope

今天遇到一个应用场景:

在需要在自定义的Interceptor中判断用户密码是否过期,如果过期,则重定向到修改密码页,强制修改密码,同时给出提示:“您的密码已过期,请修改密码”

判断逻辑很简单,但是重定向的时候需要前台有消息提示,如果是在Controller中,可以在方法上注入RedirectAttributes参数,但是Interceptor中默认没有这个参数,那么我们如何实现RedirectAttributes的flashMessage功能呢?

通过跟踪Spring源码,发现了实现方法:

FlashMap flashMap = new FlashMap();
flashMap.put('warning', "密码已过期,请先修改密码!");
FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);
flashMapManager.saveOutputFlashMap(flashMap, request, response);

搞定!


 
 
posted @ 2019-10-08 08:37  sg夜游神  阅读(207)  评论(0编辑  收藏  举报