0

我有一個使用SpringMVC和Thymeleaf的spring啓動項目。我在每個頁面上都包含一個layout.html中定義的頁腳。無論如何要在該頁腳上包含一個顯示每個頁面「狀態」的呼叫。通過這種方式瀏覽網站時,頁面頁腳將始終顯示所需的信息?Thymeleaf SpringMVC頁腳找不到控制器

我有一個REST控制器,把一個狀態對象:

@Controller 
public class StatusController { 

@RequestMapping(value = "/status", method = RequestMethod.GET) 
public String get(Model model) { 

    Status status = new Stauts; 
    LocalDate lastUpdate = statusRepository.findByLastUpdate(); 
    ... 
    // do some work to update the status object 
    model.addAttribute(STATUS, status); 
    return "status"; 
} 

我有一個在我的footer.html這個定義:

<div th:fragment="foot"> 
    <div id="footer"> 
     <div class="container"> 
      <p class="muted credit"> 
      <form action="refreshData" th:action="@{/status}" method="get"></form> 
      Last update status: <span th:text="${status.status}" class="text-info"></span> 
      </p> 
     </div> 
    </div> 
</div> 

,然後將每個頁面包含頁腳這樣:

... 

<div th:include="layout :: foot"></div> 

</body> 

我把一個斷點在我的控制器和它的不叫,我總是得到這個excepti在頁面加載:

org.springframework.expression.spel.SpelEvaluationException: EL1007E:(POS 0):屬性或字段 '狀態' 不能爲null找到

我不知道控制器永遠不會被調用,因爲我必須使用類似jQuery的東西來進行Ajax調用,或者因爲我在layout.html中有這個,並且包含調用(這似乎不太可能)?

回答

0

CURRENT:

<span th:text="${status.status}" class="text-info"> 

CHANGE TO

<span th:text="${status}" class="text-info"> 

這會在你已經將狀態設置狀態= null,則控制器顯示空

;並將其設置爲模型映射到屬性狀態「 因此$ {status}被評估爲null(這只是model.get(」status「))。$ {status.status}將爲null.status。 在 「狀態」導致不能在空

+0

有關更改原因的說明在此處很有用 – StormeHawke 2014-10-09 15:33:30

+0

但是從不調用控制器,因此Status對象從不返回。我將更新我的問題以顯示狀態對象在返回之前被實例化。 – sonoerin 2014-10-09 17:43:53

1

被發現在Spring MVC你只有每頁/調用一個控制器。你不能調用幾個控制器在一杆。我相信這是你的問題。

你有多種可能性:

  • 要麼你必須將這個狀態變量合併到每個cont滾自己。

  • 創建準備模型屬性狀態,並應用到每個控制器(默認)

  • 使用您的頁腳服務呼叫獲取類似狀態的ControllerAdvice:日:文本=「$ {@ statusService .status}「

我爲自己喜歡這些全球可用信息的服務方法。

+0

謝謝Martin,我創建了一個狀態服務,它只返回一個Status對象供頁面讀取。這似乎工作得很好,但我想知道是否有更乾淨的方法來做到這一點。感覺就像我穿越了邊界或什麼的。也許我只是很驚訝這個簡單的解決方案工作得如何:)無論如何,感謝您的快速和有益的建議。 – sonoerin 2014-10-13 12:42:28

+0

您可以引入像「UIService」這樣的自定義「Service」註釋,並將這些服務僅保留在servlet上下文中。這有助於爲我識別這些服務。 – 2014-10-13 14:26:26