很抱歉标题有误。我想不出更好的措辞了。
有没有办法设置Spring将提供页面的默认Model,而不首先在@RequestMapping方法中将其作为参数检索?
我使用方面来获取控制器方法的返回值(返回视图),并将其插入到模型中,然后呈现一个不同的全局视图,其中包括我添加到模型中的内容。这在将Model作为参数请求的方法上工作得很好。
但是,我也希望能够捕获所有未显式请求模型的方法,并仍然将返回值插入其中(通过@AfterReturning建议)。有什么想法吗?
发布于 2012-12-03 06:14:14
我不会在HttpServletRequest上使用@Autowired,因为它会让未来开发线程安全代码的开发人员感到困惑。
相反,您应该使用@ModelAttribute或Interceptor。
@ModelAttribute
请参阅:http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args
但是您可以这样做,并将此方法添加到您的控制器中:
@ModelAttribute
public preloadModel(HttpServletRequest request, ModelMap model) {
//Add stuff to model.
}拦截器
请参阅:http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor
public class PreloadModelInterceptor extends HandlerInterceptorAdapter {
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler,
ModelAndView modelAndView) throws Exception {
// add model attibutes for your view to see but not your controller
}
}发布于 2012-12-03 00:16:44
好吧,我找到了一个变通方法。或者,这也可能是底层Spring框架所做的一切。我只是在HttpServletRequest中自动连接并调用了setAttribute。似乎工作得很好。
https://stackoverflow.com/questions/13666494
复制相似问题