SlideShare a Scribd company logo
Spring Teplates
Thymeleaf & Spring framework
History
Servlets
Hello!
public class HelloWorldServlet extends HttpServlet {
protected void doGet(request, response) {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>"); out.println("<head>");
out.println("<title>Hello!</title>");
out.println("</head>");
out.println("<body bgcolor="white">");
out.println("</body>");
out.println("</html>");
}
}
Html symbols are writing directly to the browser from java code.
Servlets
Hello!
public class HelloWorldServlet extends HttpServlet {
protected void doGet(request, response) {
request.getRequestDispatcher("/login.jsp").
forward(request, response);
}
}
Html code saved separately from java code
and can be dynamically changed before sending to browser . It’s good.
<html>
<head>
<title>Hello!</title>
</head>
<body bgcolor=“gray">
<h1>Hello!</h1>
</body>");
</html>
Java Servlet-JSP Architecture
Server Hello World!
Java
Jasper
JSPs
Servlet
container
Templates
Template – document or parts of
document with basic configuration.
Table
with dynamic
content
Left
menu
Spam
Header
Footer
Spring templates.
Apache Velocity
FreeMarker
Rythm
Thymeleaf
 3.8 seconds
 4.8 seconds
 3 seconds
 43.2 seconds
Results obtained after testing with benchmarking tool
for 10000 requests.
Thymeleaf.
Thymeleaf integration with Spring framework.
Custom properties
 Core is a DOM processing engine.
 It is based on XML tags and attributes.
 XML/Valid XML/XHTML/Valid XHTML/HTML5/Legacy
HTML5 processor.
 Allows a fast processing of templates by intelligent caching
of parsed files.
 Not complex syntax.
Syntax compare
FreeMarker syntax:
<table>
<#list animals as animal>
<#if animals.python.price != 0>
<tr>
<td>${animal.name}<td>${animal.price}
</tr>
</#if>
</#list>
</table>
ApacheVelocity syntax:
<table>
#foreach($mud in $mudsOnSpecial)
#if($customer.hasPurchased($mud))
<tr>
<td>$flogger.getPromo($mud)</td>
</tr>
#end
#end
</table>
Syntax compare
Thymeleaf syntax:
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>IN STOCK</th>
</tr>
<tr th:each="prod : ${prods}">
<td th:text="${prod.name}">Onions</td>
<td th:text="${prod.price}">2.41</td>
<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>
</table>
Integration with Spring framework
Spring application context:
<bean id="templateResolver"
class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
Html file template:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
Standard dialect
Expressions:
 Variable Expressions: ${...}
 Selection Variable Expressions: *{...}
 Message Expressions: #{...}
 Link URL Expressions: @{...}
 If-then: (if) ? (then)
 If-then-else: (if) ? (then) : (else)
 Default: (value) ?: (defaultvalue)
Using with basic objects:
 #ctx : the context object.
 #vars: the context variables.
 #locale : the context locale.
 #httpServletRequest : (only in Web Contexts) the
HttpServletRequest object.
 #httpSession : (only in Web Contexts) the
HttpSession object.
Expression Utility Objects:
 #dates : utility methods for java.util.Date objects: formatting, component extraction, etc.
 #calendars : analogous to #dates , but for java.util.Calendar objects.
 #numbers : utility methods for formatting numeric objects.
 #strings : utility methods for String objects: contains, startsWith, prepending/appending, etc.
 #objects : utility methods for objects in general.
 #bools : utility methods for boolean evaluation.
 #arrays : utility methods for arrays.
 #lists : utility methods for lists.
 #sets : utility methods for sets.
 #maps : utility methods for maps.
 #aggregates : utility methods for creating aggregates on arrays or collections.
 #messages : utility methods for obtaining externalized messages inside variables expressions, in the
same way as they would be obtained using #{…} syntax.
 #ids : utility methods for dealing with id attributes that might be repeated.
Dialect extension:
<bean id="templateEngine"
class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/>
</set>
</property>
</bean>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:sec=“http://www.thymeleaf.org/thymeleaf-extras-springsecurity4”
xmlns:th="http://www.thymeleaf.org">
Messages internationalization
Application context:
<bean id="messageSource“
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value=“classpath:messages" />
</bean>
Class path:
Fragmentation
footer.html
...
<div th:fragment=“ftr">
Footer
</div>
<div id=“copyrights">
copyrights
</div>
...
Index.html
<body>
...
<div th:include="footer :: ftr"></div>
<div th:include="footer :: #copyrights"></div>
</body>
<div th:fragment="frag (onevar,twovar)">
<p th:text="${onevar} + ' - ' + ${twovar}">...</p>
</div>
<div th:include="::frag (onevar=${value1},twovar=${value2})">
Usage Examples
Object expression:
Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">11 March
2016</span>
Links usage:
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>
<a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a>
Conditions usage:
<div th:if="${user.isAdmin()} == false"> ...-
<div th:if="${user.isAdmin() == false}> ... - Spring EL
<tr th:class="${row.even}? 'class-name'"> ...
<tr th:class="${1 > 0}? 'Yes' : 'No'"> ...
Default expression:
<span th:text=“${value}?: 'no value specified'">Some value</span>
Setting attribute:
<input type="submit" value="Subscribe me!" th:attr="value=#{subscribe.submit}"/>
Forms:
<form action="subscribe.html" th:action="@{/subscribe}">
Iteration:
<tr th:each="item : ${list}">
<td th:text="${item.name}">Onions</td>
<td th:text="${item.count}">2.41</td>
</tr>
Local variable:
<div th:with="firstPer=${persons[0]},secondPer=${persons[1]}">
<span th:text="${secondPer.name}">Some Name</span>.
</div>
Set values to JavaScript:
<script th:inline="javascript">
/*<![CDATA[*/
...
var username = /*[[${session.user.name}]]*/ ‘User';
...
/*]]>*/
</script>
Switch:
<div th:switch="${user.role}">
<p th:case="'admin'">User is an administrator</p>
<p th:case="#{roles.manager}">User is a manager</p>
</div>
Summary
Advatages:
 Java template engine for XML, XHTML and HTML5.
 Works both in web and non-web (offline) environments. No hard dependency
on the Servlet API.
 Several template modes: XML, XHTML 1.0 and 1.1, HTML5:
 Internationalization support.
 Parsed template cache
 Is extensible
 Not very complex in usage
 Many documentation
Disadvatages:
 It's slowly than other templates.
The End.

More Related Content

PDF
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
PDF
Javascript MVC & Backbone Tips & Tricks
PDF
Documenting from the Trenches
KEY
Summer - The HTML5 Library for Java and Scala
PDF
Associations & JavaScript
PPTX
Html5 and web technology update
PPT
JS-05-Handlebars.ppt
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
Javascript MVC & Backbone Tips & Tricks
Documenting from the Trenches
Summer - The HTML5 Library for Java and Scala
Associations & JavaScript
Html5 and web technology update
JS-05-Handlebars.ppt

Similar to 68837.ppt (20)

PPTX
Building a friendly .NET SDK to connect to Space
PDF
Introduction to Spring MVC
PDF
A mobile web app for Android in 75 minutes
PDF
03 form-data
PDF
Rails 3 overview
PPTX
jQuery, CSS3 and ColdFusion
PDF
Mojolicious, real-time web framework
PDF
Local data storage for mobile apps
PPTX
Web Technologies - forms and actions
PPTX
Java Technology
PDF
JavaServer Faces 2.0 - JavaOne India 2011
PDF
05 status-codes
ODP
A Complete Tour of JSF 2
PDF
Build powerfull and smart web applications with Symfony2
PDF
Broadleaf Presents Thymeleaf
KEY
Building a real life application in node js
PDF
Local storage in Web apps
PDF
Laravel 8 export data as excel file with example
PPT
Play!ng with scala
PPTX
Writing HTML5 Web Apps using Backbone.js and GAE
Building a friendly .NET SDK to connect to Space
Introduction to Spring MVC
A mobile web app for Android in 75 minutes
03 form-data
Rails 3 overview
jQuery, CSS3 and ColdFusion
Mojolicious, real-time web framework
Local data storage for mobile apps
Web Technologies - forms and actions
Java Technology
JavaServer Faces 2.0 - JavaOne India 2011
05 status-codes
A Complete Tour of JSF 2
Build powerfull and smart web applications with Symfony2
Broadleaf Presents Thymeleaf
Building a real life application in node js
Local storage in Web apps
Laravel 8 export data as excel file with example
Play!ng with scala
Writing HTML5 Web Apps using Backbone.js and GAE
Ad

More from BruceLee275640 (7)

PPTX
Git_new.pptx
PDF
introductiontogitandgithub-120702044048-phpapp01.pdf
PPT
fdocuments.in_introduction-to-ibatis.ppt
PPT
Utility.ppt
PDF
springtraning-7024840-phpapp01.pdf
PPTX
java150929145120-lva1-app6892 (2).pptx
PPTX
life science.pptx
Git_new.pptx
introductiontogitandgithub-120702044048-phpapp01.pdf
fdocuments.in_introduction-to-ibatis.ppt
Utility.ppt
springtraning-7024840-phpapp01.pdf
java150929145120-lva1-app6892 (2).pptx
life science.pptx
Ad

Recently uploaded (20)

PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
1. Introduction to Computer Programming.pptx
PDF
DP Operators-handbook-extract for the Mautical Institute
PPTX
Chapter 5: Probability Theory and Statistics
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Hybrid model detection and classification of lung cancer
PDF
A comparative study of natural language inference in Swahili using monolingua...
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Heart disease approach using modified random forest and particle swarm optimi...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
gpt5_lecture_notes_comprehensive_20250812015547.pdf
cloud_computing_Infrastucture_as_cloud_p
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Enhancing emotion recognition model for a student engagement use case through...
A novel scalable deep ensemble learning framework for big data classification...
Web App vs Mobile App What Should You Build First.pdf
NewMind AI Weekly Chronicles - August'25-Week II
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
1. Introduction to Computer Programming.pptx
DP Operators-handbook-extract for the Mautical Institute
Chapter 5: Probability Theory and Statistics
Building Integrated photovoltaic BIPV_UPV.pdf
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Programs and apps: productivity, graphics, security and other tools
Unlocking AI with Model Context Protocol (MCP)
Hybrid model detection and classification of lung cancer
A comparative study of natural language inference in Swahili using monolingua...
TLE Review Electricity (Electricity).pptx
Heart disease approach using modified random forest and particle swarm optimi...

68837.ppt

  • 1. Spring Teplates Thymeleaf & Spring framework
  • 3. Servlets Hello! public class HelloWorldServlet extends HttpServlet { protected void doGet(request, response) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello!</title>"); out.println("</head>"); out.println("<body bgcolor="white">"); out.println("</body>"); out.println("</html>"); } } Html symbols are writing directly to the browser from java code.
  • 4. Servlets Hello! public class HelloWorldServlet extends HttpServlet { protected void doGet(request, response) { request.getRequestDispatcher("/login.jsp"). forward(request, response); } } Html code saved separately from java code and can be dynamically changed before sending to browser . It’s good. <html> <head> <title>Hello!</title> </head> <body bgcolor=“gray"> <h1>Hello!</h1> </body>"); </html>
  • 5. Java Servlet-JSP Architecture Server Hello World! Java Jasper JSPs Servlet container
  • 7. Template – document or parts of document with basic configuration. Table with dynamic content Left menu Spam Header Footer
  • 8. Spring templates. Apache Velocity FreeMarker Rythm Thymeleaf  3.8 seconds  4.8 seconds  3 seconds  43.2 seconds Results obtained after testing with benchmarking tool for 10000 requests.
  • 10. Custom properties  Core is a DOM processing engine.  It is based on XML tags and attributes.  XML/Valid XML/XHTML/Valid XHTML/HTML5/Legacy HTML5 processor.  Allows a fast processing of templates by intelligent caching of parsed files.  Not complex syntax.
  • 11. Syntax compare FreeMarker syntax: <table> <#list animals as animal> <#if animals.python.price != 0> <tr> <td>${animal.name}<td>${animal.price} </tr> </#if> </#list> </table> ApacheVelocity syntax: <table> #foreach($mud in $mudsOnSpecial) #if($customer.hasPurchased($mud)) <tr> <td>$flogger.getPromo($mud)</td> </tr> #end #end </table>
  • 12. Syntax compare Thymeleaf syntax: <table> <tr> <th>NAME</th> <th>PRICE</th> <th>IN STOCK</th> </tr> <tr th:each="prod : ${prods}"> <td th:text="${prod.name}">Onions</td> <td th:text="${prod.price}">2.41</td> <td th:text="${prod.inStock}? #{true} : #{false}">yes</td> </tr> </table>
  • 13. Integration with Spring framework Spring application context: <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver"> <property name="prefix" value="/WEB-INF/templates/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML5" /> </bean> <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> </bean> Html file template: <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  • 14. Standard dialect Expressions:  Variable Expressions: ${...}  Selection Variable Expressions: *{...}  Message Expressions: #{...}  Link URL Expressions: @{...}  If-then: (if) ? (then)  If-then-else: (if) ? (then) : (else)  Default: (value) ?: (defaultvalue) Using with basic objects:  #ctx : the context object.  #vars: the context variables.  #locale : the context locale.  #httpServletRequest : (only in Web Contexts) the HttpServletRequest object.  #httpSession : (only in Web Contexts) the HttpSession object.
  • 15. Expression Utility Objects:  #dates : utility methods for java.util.Date objects: formatting, component extraction, etc.  #calendars : analogous to #dates , but for java.util.Calendar objects.  #numbers : utility methods for formatting numeric objects.  #strings : utility methods for String objects: contains, startsWith, prepending/appending, etc.  #objects : utility methods for objects in general.  #bools : utility methods for boolean evaluation.  #arrays : utility methods for arrays.  #lists : utility methods for lists.  #sets : utility methods for sets.  #maps : utility methods for maps.  #aggregates : utility methods for creating aggregates on arrays or collections.  #messages : utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.  #ids : utility methods for dealing with id attributes that might be repeated.
  • 16. Dialect extension: <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> <property name="additionalDialects"> <set> <bean class="org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect"/> </set> </property> </bean> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:sec=“http://www.thymeleaf.org/thymeleaf-extras-springsecurity4” xmlns:th="http://www.thymeleaf.org">
  • 17. Messages internationalization Application context: <bean id="messageSource“ class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value=“classpath:messages" /> </bean> Class path:
  • 18. Fragmentation footer.html ... <div th:fragment=“ftr"> Footer </div> <div id=“copyrights"> copyrights </div> ... Index.html <body> ... <div th:include="footer :: ftr"></div> <div th:include="footer :: #copyrights"></div> </body> <div th:fragment="frag (onevar,twovar)"> <p th:text="${onevar} + ' - ' + ${twovar}">...</p> </div> <div th:include="::frag (onevar=${value1},twovar=${value2})">
  • 19. Usage Examples Object expression: Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">11 March 2016</span> Links usage: <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a> <a th:href="@{'/details/'+${user.login}(orderId=${o.id})}">view</a> Conditions usage: <div th:if="${user.isAdmin()} == false"> ...- <div th:if="${user.isAdmin() == false}> ... - Spring EL <tr th:class="${row.even}? 'class-name'"> ... <tr th:class="${1 > 0}? 'Yes' : 'No'"> ...
  • 20. Default expression: <span th:text=“${value}?: 'no value specified'">Some value</span> Setting attribute: <input type="submit" value="Subscribe me!" th:attr="value=#{subscribe.submit}"/> Forms: <form action="subscribe.html" th:action="@{/subscribe}"> Iteration: <tr th:each="item : ${list}"> <td th:text="${item.name}">Onions</td> <td th:text="${item.count}">2.41</td> </tr>
  • 21. Local variable: <div th:with="firstPer=${persons[0]},secondPer=${persons[1]}"> <span th:text="${secondPer.name}">Some Name</span>. </div> Set values to JavaScript: <script th:inline="javascript"> /*<![CDATA[*/ ... var username = /*[[${session.user.name}]]*/ ‘User'; ... /*]]>*/ </script> Switch: <div th:switch="${user.role}"> <p th:case="'admin'">User is an administrator</p> <p th:case="#{roles.manager}">User is a manager</p> </div>
  • 22. Summary Advatages:  Java template engine for XML, XHTML and HTML5.  Works both in web and non-web (offline) environments. No hard dependency on the Servlet API.  Several template modes: XML, XHTML 1.0 and 1.1, HTML5:  Internationalization support.  Parsed template cache  Is extensible  Not very complex in usage  Many documentation Disadvatages:  It's slowly than other templates.