在Spring MVC中设置全局模型属性的最佳实践是什么? [英] What are the best practices around setting global model attributes in Spring MVC?

查看:137
本文介绍了在Spring MVC中设置全局模型属性的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据驱动(缓存)菜单,它是一个全局组件.我希望能够为每个请求注入菜单项,因为每个页面都将使用它.放置它的最佳位置是什么?我正在使用基于注释的Spring3.我能想到的最佳解决方案是使用OncePerRequestFilter并将其添加到该子类或对Controller进行子类化,但不确定如何使用@Controller批注来做到这一点.

I have a menu that is data driven(cached) and it is a global component. I want to be able to inject the menu items for every request since every page is going to be using it. What is the best place to put it? I'm using annotation based Spring3. Best solution I can think of is using a OncePerRequestFilter and adding it there or sub-classing the Controller, but not sure how to do that with @Controller annotation.

推荐答案

我可以想到两个简单的选择:

I can think of two easy options:

每个@Controller类都将数据公开为以@ModelAttribute注释的方法,例如

Each @Controller class exposes the data as a method annotated with @ModelAttribute, e.g.

@ModelAttribute
public MyData getMyData() {
  ...
}

但是,如果您有多个控制器,那并不是很好.此外,这还会给每个重定向的URL上的myData编码提供恼人的副作用

That's not really nice if you have multiple controllers, though. Also, this has the annoying side-effect of encoding the myData on to the URL for every redirect

我建议改为实现HandlerInterceptor,并以这种方式将数据公开给每个请求.您不能使用任何喜欢注释的方法,但是最好通过这种方式将其与业务逻辑分开.这与您的OncePerRequestFilter想法类似,但更多的是Spring-y.

I suggest instead that implement a HandlerInterceptor, and expose the data to every request that way. You can't use any annotation-lovin, but it's better separated from your business logic this way. This is similar to your OncePerRequestFilter idea, but a but more Spring-y.

这篇关于在Spring MVC中设置全局模型属性的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆