【问题标题】:Spring MVC parent template model componentSpring MVC 父模板模型组件
【发布时间】:2016-04-21 23:37:17
【问题描述】:

我正在使用 Spring MVC 4,并且我正在使用一个模板构建一个站点,该模板需要跨页面的多个通用组件,例如登录状态、购物车状态等。控制器功能的示例如下:

@RequestMapping( path = {"/"}, method=RequestMethod.GET)    
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView("index");
        mav.addObject("listProducts", products );
        mav.addObject("listCategories",  menuCategoriasUtils.obtainCategories());
        return mav;
    }

什么是提供这些不属于我们当前调用的控制器的元素的好方法/模式,这样我们就不会在每个控制器的每个方法中一遍又一遍地重复 不相关 操作?

谢谢!

【问题讨论】:

    标签: java spring spring-mvc model-view-controller template-engine


    【解决方案1】:

    有几种方法可以在视图中显示常见数据。其中之一是使用@ModelAttributte 注释。

    假设您有用户登录,需要在每个页面上显示。此外,您有安全服务,您将从那里获得有关当前登录的安全信息。您必须为所有控制器创建父类,这将添加公共信息。

    public class CommonController{
    
        @Autowired
        private SecurityService securityService;
    
        @ModelAttribute
        public void addSecurityAttributes(Model model){
            User user = securityService.getCurrentUser();
            model.addAttribute("currentLogin", user.getLogin());
    
            //... add other attributes you need to show
        }
    
    }
    

    注意,您不需要用@Controller 注释标记CommonController。因为您永远不会直接将其用作控制器。其他控制器必须继承自CommonController

    @Controller
    public class ProductController extends CommonController{
    
        //... controller methods
    }
    

    现在您应该什么都不做,将currentLogin 添加到模型属性。它将自动添加到每个模型中。您可以在视图中访问用户登录:

    ...
    <body>
       <span>Current login: ${currentLogin}</span>
    </body>
    

    更多关于@ModelAttribute注解的使用细节你可以找到here in documentation

    【讨论】:

    • 非常有用的答案。正是我想要的。
    • 谢谢,这是我正在寻找的解决方案。其他解决方案(主要使用拦截器)不起作用,这个可以。
    猜你喜欢
    • 2013-08-27
    • 2017-03-18
    • 1970-01-01
    • 2011-05-20
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多