Post / redirect / GET 解决方案如果适合您,则有效。
但是,我遇到了类似的情况,在请求处理之后(主要是跟踪信息),我的所有控制器都需要编写模型属性。我所做的是注册一个自定义接口(例如AdditionalModelDataSupplier
),我将其应用于所有需要提供附加数据的控制器。该接口将具有这样的方法:
void provideAdditionalData(Model model, HttpServletRequest request);
现在,我编写了一个拦截器,在该postHandle
方法中检查该接口的 Controller bean 并调用该方法:
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception {
AdditionalModelDataSupplier modelDataSupplier = findAdditionalModelDataSupplier(handler);
if (modelDataSupplier != null) {
final ModelMap modelMap = modelAndView.getModelMap();
final Model targetModel;
if (modelMap instanceof Model) {
targetModel = (Model) modelMap;
} else {
// the modelmap doesn't implement model, so we need to provide a wrapper view
targetModel = new ForwardingModel(modelMap);
}
modelDataSupplier.provideAdditionalData(targetModel, request);
}
}
@Nullable
private static AdditionalModelDataSupplier findAdditionalModelDataSupplier(final Object handler) {
if (handler instanceof AdditionalModelDataSupplier) {
return (AdditionalModelDataSupplier) handler;
}
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Object bean = handlerMethod.getBean();
if (bean instanceof AdditionalModelDataSupplier) {
return (AdditionalModelDataSupplier) bean;
}
}
return null;
}
(ForwardingModel
上面提到的类很容易创建,它只是将所有内容委托给ModelMap
)