使用
HandlerInterceptor
.
public class CategoryListAddInterceptor extends HandlerInterceptorAdapter {
@Autowired
private CategoryDao categoryDao; //for example
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
modelAndView.getModel().put("categoryList", categoryDao.getPostCategoryList());
}
}
在配置XML文件中,添加:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/demo/**"/> <!-- can add exclude patterns if needed -->
<bean class="package.name.CategoryListAddInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
更新:
正如你所得到的
NullPointerException
在呼叫时
modelAndView.getModel()
你可以这样做来实现同样的事情:
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
request.setAttribute("categoryList", categoryDao.getPostCategoryList());
}