備忘録:Spring BootでHandlerInterceptorを用いてattributeを追加する際はredirectを除外する

数時間ドはまりしていたのでメモ。

全Controllerにて共通にattributeを追加する際にHandlerInterceptor#postHandleを用いる方法がありますが、これでattributeを追加した場合、redirect時に遷移先ページのURLパラメータにattributeが付与されている状態となっておりました。
例えば、全Controllerにて"key"という名前のattributeを値"value"で追加する場合、/hoge/にredirectすると/hoge/?key=valueというURLに遷移されたような挙動となりました。

なので、このようにします。

class CommonAttributeInterceptor: HandlerInterceptor {
    override fun postHandle(
            request: HttpServletRequest,
            response: HttpServletResponse,
            handler: Any,
            modelAndView: ModelAndView?) {
        modelAndView?.apply {
            if (this.viewName?.startsWith("redirect:") != true) {
                this.modelMap.addAttribute("key", "value")
            }
        }
    }
}

Spring Bootのバージョンは古めの2.2.2.RELEASEです。