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