问题
I usually add objects in my jsp requestScopes using Controllers.
For example, if I need to list categories in "localhost/products/viewall", I simply change my ProductsController adding something like
@RequestMapping("/products/viewall")
public void viewCategories(Model model) {
List<Category> categories = service.findAllCategories();
model.addAttribute("categories", categories);
}
so, this method adds a list of categories to my requestScope.
I need to do the same, but for all the pages of the website (since the variable I need will be used in the layout of the site).
How can I add something to all the pages requestScopes with Spring?
回答1:
I think you have at least two possible options for this:
Using an MVC Interceptor. With an interceptor you can perform common operations for all requests. You can extend HandlerInterceptorAdapter and add common model data in
postHandleUsing the
@ModelAttributeannotation within an Controller. You can use this to add common data for all request mappings within a controller. You can also use an @ControllerAdvice (with@ModelAttributeannotated methods inside) if you want provide model data to all controllers. The section Using @ModelAttribute on a method should provide some additional information for this.
来源:https://stackoverflow.com/questions/18109119/how-to-store-variables-in-all-pages-requestscopes-within-spring