Reputation: 4805
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);
}
}
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?
Upvotes: 2
Views: 5886
Reputation: 2245
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);
}
}
}
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>
Upvotes: 6
Reputation: 4466
you can extend HandlerInterceptorAdapter and add common modelAttributes thr
Upvotes: 1