Spring MVC視圖層:thymeleaf vs. JSP


本文對比了同一Spring MVC工程中相同頁面(一個訂閱表單)分別采用Thymeleaf和JSP(包括JSP、JSTL、Spring tag lib)兩種方式的實現。

本文的所有代碼來自一個可運行的應用。你可以從文檔頁面下載該應用程序的源代碼。

Common requirements

顧客通過一個表單添加到消息列表中,包含下面兩個域:

  • Email地址
  • 訂閱類型(接收所有郵件、每日摘要)

要求該頁面支持HTML5且完全國際化,國際化信息從Spring框架中配置的MessageSource對象中抽取所有的文本和消息。

該應用包含兩個@Controller,二者含有相同的代碼,只是跳轉到不同的view:

  • SubscribeJsp用於JSP頁面(subscribejsp視圖)
  • SubscribeTh用於Thymeleaf頁面(subscribeth視圖)

在模型(model)中包含下列類:

  • Subscription:form-backing bean,包含兩個域:String email和SubscriptionType subscriptionType。
  • SubscriptionType:一個枚舉類型,表單中subscriptionType域的值,可取的值包含ALL_EMAILS和DAILY_DIGEST。

(本文我們僅關注JSP和Thymeleaf模板代碼的討論。如果你想了解controller代碼和Spring配置的實現細節,請自行查看下載包中的源代碼)

使用JSP實現(Doing it with JSP)

這是頁面:

下面是JSP代碼,使用了JSTL(core)和Spring(tags和form) JSP標簽庫:

 

<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %><%@
taglib prefix="s" uri="http://www.springframework.org/tags" %><%@
taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@
page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html>
 
<html>
 
<head>
    <title>Spring MVC view layer: Thymeleaf vs. JSP</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" href="<s:url value='/css/thvsjsp.css' />"/>
</head>
 
<body>
 
<h2>This is a JSP</h2>
 
<s:url var="formUrl" value="/subscribejsp" />
<sf:form modelAttribute="subscription" action="${formUrl}">
 
    <fieldset>
 
        <div>
            <label for="email"><s:message code="subscription.email" />: </label>
            <sf:input path="email" />
        </div>
        <div>
            <label><s:message code="subscription.type" />: </label>
            <ul>
                <c:forEach var="type" items="${allTypes}" varStatus="typeStatus">
                    <li>
                        <sf:radiobutton path="subscriptionType" value="${type}" />
                        <label for="subscriptionType${typeStatus.count}">
                            <s:message code="subscriptionType.${type}" />
                        </label>
                    </li>
                </c:forEach>
            </ul>
        </div>
 
        <div class="submit">
            <button type="submit" name="save"><s:message code="subscription.submit" /></button>
        </div>
 
    </fieldset>
 
</sf:form>
 
</body>
 
</html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM