对不起,这个标题。我想不出更好的措辞。
是否有任何方法可以设置 Spring 将提供页面的默认模型,而无需首先将其作为 @RequestMapping 方法中的参数进行检索?
我使用方面来获取 Controller 方法的返回值(返回 View )并将其插入到模型中,然后渲染一个不同的全局 View ,其中包含我添加到模型中的内容。这对于请求模型作为参数的方法来说效果很好。
但是,我还希望能够捕获所有未显式请求模型的方法,并且仍然将返回值插入其中(通过 @AfterReturning 建议)。有什么想法吗?
最佳答案
我不会在 HttpServletRequest
上使用@Autowired
,因为它会让 future 处理线程安全代码的开发人员感到困惑。
相反,您应该使用@ModelAttribute
或Interceptor
。
@ModelAttribute
但是您可以执行类似的操作并将此方法添加到您的 Controller 中:
@ModelAttribute
public preloadModel(HttpServletRequest request, ModelMap model) {
//Add stuff to model.
}
拦截器
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
}
}
关于java - (Java) 不使用参数或 ModelAndView 访问 Spring Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13666494/