2

我正在使用Spring MVC 4,并且正在构建一个模板,需要跨页面的多个常用组件,例如登录状态,购物车状态等。控制器函数的示例会是这样的:Spring MVC父模板模型组件

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

这将是一个很好的方法/模式养活那些不属于我们目前正在打电话,所以我们不要过度重复和超过无关操作中的每一个方法控制这些元素每个控制器?

谢谢!

回答

3

有几种方法可以在视图中显示常见数据。其中之一是使用@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

+0

非常有用的答案。正是我在找的东西。 – santiageitorx

+0

谢谢,这是我一直在寻找的解决方案。其他解决方案(主要是使用拦截器)不起作用,这是一个解决方案。 – mxmx