How to store variables in all pages requestScopes within Spring

落花浮王杯 提交于 2019-12-13 08:39:33

问题


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 postHandle

  • Using the @ModelAttribute annotation 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 @ModelAttribute annotated 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!