如何设置控制器范围的全局变量 [英] How to set Controller-wide global variables
本文介绍了如何设置控制器范围的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前我使用 @ModelAttribute
在我的 @Controller
中设置全局变量(例如页脚的推文):
Currently I use @ModelAttribute
to set global variables (e.g. tweets for the footer) in my @Controller
:
public @Controller class MainController {
public @ModelAttribute void global(ModelMap map) {
map.addAttribute("tweets", /*...*/null);
}
}
但是在创建另一个Controller时,它们在逻辑上已经消失了保持清洁和分离:
But they're logically gone when creating another Controller to keep things clean and separated:
public @Controller class GalleryController {
// ...
}
设置全局变量控制器范围的最佳做法是什么?
What's the best practice to set global variables Controller wide?
推荐答案
如果你想把一些数据放到每个页面上,很容易使用拦截器:
If you want to put some data to every page it is easy to use interceptor:
public class PagePopulationInterceptor extends HandlerInterceptorAdapter {
@Autowired
private UserService userService;
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if(modelAndView != null) {
User user = userService.findOne(request);
modelAndView.addObject("myUserProfile", user);
}
}
}
制作这项工作还在webmvc-config.xml中声明拦截器(webapp的弹簧配置):
To make this work also declare interceptor in webmvc-config.xml (spring configuration for webapp):
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.yourcompany.yourapp.util.PagePopulationInterceptor" />
</mvc:interceptor>
<!-- other interceptors (locale, theme and so on) -->
</mvc:interceptors>
这篇关于如何设置控制器范围的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文