另一种选择是将拦截器添加到您的 MVC 配置中。例如,此拦截器检索用户的未读会话数,以便在其导航栏中显示它,并将其作为具有请求范围的属性存储在 HttpServletRequest 中。它也可以添加到 ModelAndView 中:
public class PageModelInterceptor extends HandlerInterceptorAdapter {
private MessagingService mailboxService;
public PageModelInterceptor() {
}
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) {
addNbConversationUpdates(request);
}
private void addNbConversationUpdates(final HttpServletRequest request) {
if (XSecurity.principal() != null) {
final int nbUpdatedConversations = mailboxService.getUpdatedConversations(XSecurity.principal().getId()).size();
request.setAttribute("nbConversationUpdates", nbUpdatedConversations);
}
}
public void setMailboxService(final MessagingService mailboxService) {
this.mailboxService = mailboxService;
}
}
这需要添加到您的 dispatcher-servlet.xml 或您的 Web 应用程序上下文声明的任何文件中。
<mvc:interceptor>
<mvc:mapping path="/ui/**" />
<bean class="com.xyz.project.web.PageModelInterceptor">
<property name="mailboxService" ref="mailboxService" />
</bean>
</mvc:interceptor>
如您所见,您可以声明路径模式,从而排除不需要这样做的 URL。