Spring MVC 父模板模型组件

Spring MVC parent template model component

我正在使用 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;
    }

最好 way/pattern 提供这些不属于我们当前调用的控制器的元素,这样我们就不会一遍又一遍地重复 无关每个控制器的每个方法中的操作?

谢谢!

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

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

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