2009-07-14 69 views
4

假設我有一個包含Cat(s)和Dog(s)等標準多態行爲的動物列表。如何爲不同類型的對象顯示不同的JSP視圖

什麼是最好的方法來顯示列表中的每一個不同的JSP視圖?

<c:forEach var='animal' items='${animals}'> 
    //show a different template per animal type 
</c:forEach> 

說實話,每個bean的#toJSP都是我不會考慮的,因爲很明顯的原因。

我很想然而使用

public interface Template{ 

    public String render() 
} 

在構造函數中傳遞的每個動物的,但我不知道要在其中創建這些對象。我想這可以在JSP內部完成,但是我出於某種原因使用這種表示法猶豫不決。

+0

該死的。看起來答案是「JSP完全吸引」。不酷。 – aaaidan 2012-03-27 02:26:32

回答

1

所以我結束了使用可用於國際化的JSP以下列方式

<fmt:message var="template" key="${animal.class.name}" /> 

template.properties文件

foo.bar.Animal = animal.jsp 
foo.bar.Cat = cat.jsp 
foo.bar.Dog = dog.jsp 

所以最終的解決方案「捆綁」看起來像這樣

<c:forEach var='animal' items='${animals}'> 
    <span> 
     <c:set var="animal" scope="request" value="${animal}"/> 
     <fmt:message var="template" key="${animal.class.name}" /> 
     <jsp:include page="${template}" /> 
    </span> 
</c:forEach> 

使用模板看起來像這樣的文件

Hello animal ${animal}! 
Hello cat ${animal}! 
Hello dog ${animal}! 
0

在Animal上聲明一個抽象方法,該方法返回一個名爲getMyJspPage()的字符串。

然後貓和狗可以返回對您可以包含的不同jsp頁面或jsp片段的引用。

1

您可以使用自定義標記,以當前的動物作爲屬性,並使用它來確定正確的觀點

1

不幸的是,在JSP中繼承和多態不工作得很好。

的最簡單,最維護的解決方案一直只是做了很多

<c:choose> 
    <c:when test="${animal.type == 'Cat'}"> 
     <my:renderCat cat="${animal}"/> 
    </c:when> 
    <c:when test="${animal.type == 'Dog'}"> 
     <my:renderDog Dog="${animal}"/> 
    </c:when> 
    ... 
</c:choose> 

,並有標籤文件(如renderDog.tag,renderCat.tag)拍攝每一個特定的動物作爲一個屬性,打電話給他們。至少它保持了調度和渲染分離。

相關問題