2015-09-11 114 views
0

在我目前的春天啓動的項目的同時,我有這樣的thymeleaf代碼:迭代兩個列表與thymeleaf

<th:block th:each="item : ${menu}"> 
... 
       <a th:href="@{/__${menu2}__/listagem}"> 
        <i class="icon-asterisk"></i> 
        <span th:utext="${item}"></span> 
       </a> 
... 
<th:block> 

在那裏我想在一個循環th:each迭代兩個列表(menumenu2)。對於menu2我試試這個:

${menu2[itemStat.index]} 

但我得到的錯誤:

org.springframework.expression.spel.SpelEvaluationException: EL1012E:(pos 5): Cannot index into a null value 

什麼是訪問循環內第二個下拉列表的正確方法?

UPDATE

  • 控制器:

    @ModelAttribute("menu") 
    public List<String> menu() throws Exception { 
        return ApplicationClasses.lista_classes_projeto(); 
    } 
    @ModelAttribute("menu2") 
    public List<Class<?>> menu2() throws Exception { 
        return ApplicationClasses.lista_classes_projeto_2(); 
    } 
    
  • ApplicationClasses:

    public static List<String> lista_classes_projeto() throws ClassNotFoundException { 
    Locale currentLocale = Locale.getDefault(); 
        ResourceBundle messages = ResourceBundle.getBundle("messages", currentLocale); 
    
    List<String> lista = new ArrayList<String>(); 
    
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); 
    scanner.addIncludeFilter(new AnnotationTypeFilter(Form.class)); 
    for (BeanDefinition bd : scanner.findCandidateComponents("com.spring.loja.model")) { 
        Class<?> clazz = Class.forName(bd.getBeanClassName()); 
        lista.add(messages.getString(clazz.getSimpleName())); 
    } 
    
    return lista; 
    } 
    
    public static List<Class<?>> lista_classes_projeto_2() throws ClassNotFoundException { 
    List<Class<?>> lista = new ArrayList<Class<?>>(); 
    
    ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); 
    scanner.addIncludeFilter(new AnnotationTypeFilter(Form.class)); 
    for (BeanDefinition bd : scanner.findCandidateComponents("com.spring.loja.model")) { 
        Class<?> clazz = Class.forName(bd.getBeanClassName()); 
        lista.add(clazz); 
    } 
    
    return lista; 
    } 
    
+0

向我們展示本節的完整代碼,因爲您目前有空白,我們必須根據它們進行假設,例如, itemStat在哪裏填充?列表還包含數據的對象還是非對象? – Aeseir

+0

@Aeseir該部分沒有任何其他相關代碼會改變代碼的理解。我在控制器中添加了關於thymeleaf代碼迭代數據源的Java代碼。 –

回答

2

由於沒有更多的細節我要做個g提供這個答案時的重要假設。

<block th:each="item,itemStat : ${menu}"> 
<span th:text="*{menu2[__${itemStat .index}__].something}"></span> // assuming its a object that has parameter called somethin 
</block> 

你的菜單2列表我相信是空的,因此也是null。

+0

是的,我確認menu2在視圖中是空的(我不明白爲什麼)。從控制器添加了Java代碼和數據源(對於菜單和菜單2 - 菜單沒問題,但菜單2沒有,儘管幾乎相同)。 –

+0

好的,我重新檢查了代碼,最後注意到我在錯誤的控制器中設置了屬性'model2'。修復後,代碼與'$ {menu2 [itemStat.index]}'一起工作 –