【问题标题】:(Java) Access Spring Model without using parameters or ModelAndView(Java) 不使用参数或 ModelAndView 访问 Spring Model
【发布时间】:2012-11-19 22:18:47
【问题描述】:

对不起标题。我想不出更好的措辞。

有什么方法可以设置默认模型,Spring 将提供页面而不首先将其作为@RequestMapping 方法中的参数检索?

我正在使用方面来获取控制器方法的返回值(返回视图)并将其插入到模型中,然后渲染一个不同的全局视图,其中包含我添加到模型中的内容。这适用于请求模型作为参数的方法。

但是,我还希望能够捕获所有未显式请求模型并仍将返回值插入其中的方法(通过@AfterReturning 建议)。有什么想法吗?

【问题讨论】:

    标签: java spring model-view-controller parameters model


    【解决方案1】:

    我不会在HttpServletRequest 上使用@Autowired,因为它会使未来从事线程安全代码的开发人员感到困惑。

    您应该使用@ModelAttributeInterceptor

    @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
        }
    }
    

    【讨论】:

    • ModelAttribute 非常适合我想要的东西。我也会看看拦截器,但我认为现在这已经足够了。谢谢。
    • 如果您想将模型属性添加到视图所需的所有控制器,拦截器非常有用。例如,我通常将用户对象绑定到拦截器中的模型。 @ModelAttribute 将仅适用于在其所在的控制器中映射的请求,但在处理的请求映射中可用(使用 @RequestMapping 的方法)。
    • 它对我有用,因为我已经有一个 BaseController 可以扩展我的所有控制器。我只是在@ModelAttribute 方法中设置必要的变量。
    【解决方案2】:

    好吧,我找到了解决方法。或者也许这就是底层 Spring 框架所做的一切。我只是在 HttpServletRequest 中自动装配并调用了 setAttribute。似乎工作正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 2018-12-15
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      相关资源
      最近更新 更多