你可以写一个org.springframework.web.servlet.HandlerInterceptor
. (或其便利子类HandlerInterceptorAdapter
)
@参见:Spring 参考章节:15.4.1 拦截请求 - HandlerInterceptor 接口
它有以下方法:
void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception;
此方法在控制器完成后和视图呈现之前调用。所以你可以使用它来添加一些属性到ModelMap
一个例子:
/**
* Add the current version under name {@link #VERSION_MODEL_ATTRIBUTE_NAME}
* to each model.
* @author Ralph
*/
public class VersionAddingHandlerInterceptor extends HandlerInterceptorAdapter {
/**
* The name under which the version is added to the model map.
*/
public static final String VERSION_MODEL_ATTRIBUTE_NAME =
"VersionAddingHandlerInterceptor_version";
/**
* it is my personal implmentation
* I wanted to demonstrate something usefull
*/
private VersionService versionService;
public VersionAddingHandlerInterceptor(final VersionService versionService) {
this.versionService = versionService;
}
@Override
public void postHandle(final HttpServletRequest request,
final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
modelAndView.getModelMap().
addAttribute(VERSION_MODEL_ATTRIBUTE_NAME,
versionService.getVersion());
}
}
}
webmvc-config.xml
<mvc:interceptors>
<bean class="demo.VersionAddingHandlerInterceptor" autowire="constructor" />
</mvc:interceptors>