SlideShare a Scribd company logo
1 of 43
Spring Essentials
Thymeleaf and Spring Controllers
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Thymeleaf
 Standard Expressions
 Forms
 Conditionals
 Loops
2. Spring Controllers
2
3
sli.do
#JavaWeb
Have a Question?
Thymeleaf
The Templating Engine
5
 Thymeleaf is a view engine used in Spring
 It allows us to:
 Use variables/collections in our views
 Execute operations on our variables
"Thymeleaf is very, very extensible, and it allows you to define your own sets of template
attributes (or even tags) with the names you want, evaluating the expressions you want in the
syntax you want and applying the logic you want. It’s more like a template engine
framework." - thymeleaf.org
What is Thymeleaf?
6
 Use Spring Initializr to import Thymeleaf, or use this
dependency in your pom.xml:
 Define the Thymeleaf library in your html file:
How to use Thymeleaf?
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
7
 You also need to change the Thymeleaf version in your
pom.xml:
Change Thymeleaf Version
<properties>
<thymeleaf.version>
3.0.2.RELEASE
</thymeleaf.version>
<thymeleaf-layout-dialect.version>
2.2.0
</thymeleaf-layout-dialect.version>
</properties>
 All Thymeleaf tags and attributes begin with th: by default
 Example of Thymeleaf attribute:
 Example of Thymeleaf tag(element processor):
 th:block is an attribute container that disappears in the HTML
8
Thymeleaf Tags and Attributes
<p th:text="Example"></p>
<th:block>
...
</th:block>
9
 Variable Expressions
 Selection Expressions
 Link (URL) Expressions
 Fragment Expressions
Thymeleaf Standard Expressions
${...}
@{...}
*{...}
~{...}
10
 Variable Expressions are executed on the context variables
 Examples:
Thymeleaf Variable Expressions
${...}
${session.user.name}
${title}
${game.id}
11
 Selection Expressions are executed on the previously selected
object
 Example:
Thymeleaf Selection Expressions
*{...}
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
//equivalent to ${book.title}
...
</div>
12
 Link Expressions are used to build URLs
 Example:
 You can also pass query string parameters:
 Create dynamic URLs
Thymeleaf Link Expressions
@{...}
<a th:href="@{/register}">Register</a>
<a th:href="@{/details(id=${game.id})}">Details</a>
<a th:href="@{/games/{id}/edit(id=${game.id})}">Edit</a>
13
 Variables in Thymeleaf are defined using the following attribute:
 Where 'var' is the name of our variable and 'pesho' it’s the value
 Variables exists only in the scope of the tag
Variables in Thymeleaf
th:with="var = 'pesho'"
<div th:with="name = ${user.name}">
<p th:text="${name}"> // valid
</div>
<p th:text="${name}"> // invalid
14
 Fragment Expressions are easy way to move around templates
 Example:
Thymeleaf Fragment Expressions
~{...}
<div th:with="frag=~{footer :: #main}">
…
<p th:insert="${frag}">
…
</div>
15
 Including entire file
 Including only a fragment
 Including fragment with parameter
 You can also use th:replace in order to replace the entire
element
Thymeleaf Fragments
th:insert="~{fragments/header}"
th:insert="~{fragments/header :: dark}"
th:insert="~{fragments/header (theme='dark')}"
16
 In Thymeleaf you can create almost normal HTML forms:
 You can have a controller that will accept an object of given
type:
Forms in Thymeleaf
<form th:action="@{/user}" th:method="post">
<input type="number" name="id"/>
<input type="text" name="name"/>
<input type="submit"/>
</form>
@PostMapping("/user")
public ModelAndView register(@ModelAttribute User user)
{ ... }
17
 You can pass objects to forms in order to use validations:
 The th:field attribute creates different attributes based on
the input type
Forms in Thymeleaf (2)
<form th:action="@{/user}" th:method="post"
th:object=${user}>
<input type="number" th:field="*{id}"/>
<input type="text" th:field="*{name}"/>
<input type="submit"/>
</form>
18
 If statements can be created in the following way:
 You can create inverted if statements using th:unless:
Conditional Statements in Thymeleaf
<div th:if="${…}">
<p>The statement is true</p>
</div>
<div th:unless="${…}">
<p>The statement is false</p>
</div>
19
 You can also create switch in which the default case is "*":
 Or use ternary operator:
Conditional Statements in Thymeleaf (2)
<div th:switch="${writer.role}">
<p th:case="'ADMIN'">The user is admin</p>
<p th:case="'MOD'">The user is moderator</p>
<p th:case="*">The user has no privileges</p>
</div>
<p th:text="${row.even} ? 'even' : 'odd'">
...
</p>
20
 Creating a for loop:
 Example:
Loops in Thymeleaf
<div th:each="element :
${#numbers.sequence(start, end, step)}">
<p th:text="${element}"></p>
</div>
<div th:each="element : ${#numbers.sequence(1, 5)}">
<p th:text="${element}"></p>
</div>
// 1 2 3 4 5
21
 Creating a for-each loop:
 Getting the iterator:
Loops in Thymeleaf (2)
<div th:each="book : ${books}">
<p th:text="*{author}"></p>
</div>
<div th:each="u, iter : ${users}" th:object="${u}">
<p th:text="|ID: *{id}, Username: *{name}|"></p>
<p th:text="|${iter.index} of ${iter.size}|"></p>
</div>
Spring Controllers
Annotations, IoC Container
23
 Defined with the @Controller annotation:
 Controllers can contain multiple actions on different routes.
Spring Controllers
@Controller
public class HomeController {
…
}
24
 Annotated with with @RequestMapping(…)
 Or
Controller Actions
@RequestMapping("/home")
public String home() {
return "home-view";
}
@RequestMapping("/home")
public ModelAndView home(ModelAndView mav) {
mav.setViewName("home-view");
return mav;
}
25
 Problem when using @RequestMapping is that it accepts all
types of request methods (get, post, put, delete, head, patch…)
 Execute only on GET requests :
Request Mapping
@RequestMapping(value="/home", method=RequestMethod.GET)
public String home() {
return "home-view";
}
26
 Easier way to create route for a GET request:
 This is alias for RequestMapping with method GET
Get Mapping
@GetMapping("/home")
public String home() {
return "home-view";
}
27
 Similar to the GetMapping there is also an alias for
RequestMapping with method POST:
 Similar annotations exist for all other types of request methods
Post Mapping
@PostMapping("/register")
public String register() {
…
}
28
 You can set all actions in a controller to start with a given
routing:
 Calling the adminPanel() will be done on route "/admin/"
Controller Routing
@Controller
@RequestMapping("/admin")
public class AdminController {
@GetMapping("/")
public String adminPanel() {
…
}
}
29
 Passing a string to the view:
 The Model object will be automatically passed to the view as
context variables and the attributes can be accessed from
Thymeleaf using the Expression syntax -
Passing Attributes to View
@GetMapping("/")
public String welcome(Model model) {
model.addAttribute("name", "Pesho");
return "welcome";
}
${name}
30
 The session will be injected from the IoC container when called:
 Later the session attributes can be accessed from Thymeleaf
using the expression syntax and the #session object:
Working with the Session
@GetMapping("/")
public String home(HttpSession httpSession) {
…
httpSession.setAttribute("id", 2);
…
}
${session.id}
31
 In order to set a cookie, we need to access the HttpResponse:
Setting a Cookie
@GetMapping("/darktheme")
public String darkTheme(HttpServletResponse httpResponse)
{
…
httpResponse.addCookie("theme", "dark");
…
}
32
 Accessing a cookie, you've set previously:
 Setting a default value
Getting a Cookie
public String index(@CookieValue("theme") String theme) {
…
}
public String index(@CookieValue(value = "theme",
defaultValue = "bootstrap.min.css") String theme ) {
…
}
33
 Accessing the HttpRequest:
 Accessing all cookies:
Http Request
public String index(HttpServletRequest httpRequest) {
…
}
public String index(HttpServletRequest httpRequest) {
Cookie[] cookies = httpRequest.getCookies();
…
}
34
 Getting a parameter from the query string:
 @RequestParam can also be used to get POST parameters
Request Parameters
@GetMapping("/details")
public String details(@RequestParam("id") Long id) {
…
}
@PostMapping("/register")
public String register(@RequestParam("name") String name)
{ … }
35
 Getting a parameter from the query string:
 Making parameter optional:
Request Parameters with Default Value
@GetMapping("/comment")
public String comment(@RequestParam(name="author",
defaultValue = "Annonymous") String author)
{ … }
@GetMapping("/search")
public String search(@RequestParam(name="sort", required
= false) String sort)
{ … }
36
 Spring will automatically try to fill objects with a form data
 The input field names must be the same as the object field
names
Form Objects
@PostMapping("/register")
public String register(@ModelAttribute UserDTO userDto) {
…
}
37
 Redirecting after POST request:
Redirecting
@PostMapping("/register")
public String register(@ModelAttribute UserDTO userDto) {
…
return "redirect:/login";
}
38
 Redirecting with query string parameters
Redirecting with Parameters
@PostMapping("/register")
public String register(@ModelAttribute UserDTO userDto,
RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute("errorId", 3);
return "redirect:/login";
}
39
 Keeping objects after redirect
Redirecting with Attributes
@PostMapping("/register")
public String register(@ModelAttribute UserDTO userDto,
RedirectAttributes redirectAttributes) {
…
redirectAttributes.addFlashAttribute("userDto",
userDto);
return "redirect:/register";
}
40
 Thymeleaf is a powerful view engine
 You can work with variables and helper objects
 You can create loops and conditional statements
 You can easily create forms
 The Spring controllers have built-in IoC container
 You can create routings on actions and controllers
 You have access to the HttpRequest, HttpResponse, HttpSession,
Cookies and others
 You can redirect between actions
Summary
?
Spring Essentials
https://softuni.bg/courses/java-mvc-frameworks-spring
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
42
Trainings @ Software University (SoftUni)
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University Foundation
 softuni.org
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg

More Related Content

Similar to Thymeleaf and Spring Controllers.ppt

Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Maurizio Pelizzone
 
Twig Brief, Tips&Tricks
Twig Brief, Tips&TricksTwig Brief, Tips&Tricks
Twig Brief, Tips&TricksAndrei Burian
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4JoeDinaso
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkBo-Yi Wu
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolGordon Forsythe
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Rene Bakx
 
Fpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directivesFpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directivesMalik Tauqir Hasan
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodesnihiliad
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress pluginAnthony Montalbano
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise7sharp9
 
Writing and Publishing Puppet Modules - PuppetConf 2014
Writing and Publishing Puppet Modules - PuppetConf 2014Writing and Publishing Puppet Modules - PuppetConf 2014
Writing and Publishing Puppet Modules - PuppetConf 2014Puppet
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindiaComplaints
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the TrenchesJonathan Wage
 

Similar to Thymeleaf and Spring Controllers.ppt (20)

Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress Use Symfony2 components inside WordPress
Use Symfony2 components inside WordPress
 
Twig Brief, Tips&Tricks
Twig Brief, Tips&TricksTwig Brief, Tips&Tricks
Twig Brief, Tips&Tricks
 
Power shell examples_v4
Power shell examples_v4Power shell examples_v4
Power shell examples_v4
 
CodeIgniter PHP MVC Framework
CodeIgniter PHP MVC FrameworkCodeIgniter PHP MVC Framework
CodeIgniter PHP MVC Framework
 
Zend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_ToolZend Framework 1.9 Setup & Using Zend_Tool
Zend Framework 1.9 Setup & Using Zend_Tool
 
Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012Twig for Drupal @ Frontendunited Amsterdam 2012
Twig for Drupal @ Frontendunited Amsterdam 2012
 
Django
DjangoDjango
Django
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
Fpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directivesFpga 06-data-types-system-tasks-compiler-directives
Fpga 06-data-types-system-tasks-compiler-directives
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodes
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress plugin
 
F# in the enterprise
F# in the enterpriseF# in the enterprise
F# in the enterprise
 
Writing and Publishing Puppet Modules - PuppetConf 2014
Writing and Publishing Puppet Modules - PuppetConf 2014Writing and Publishing Puppet Modules - PuppetConf 2014
Writing and Publishing Puppet Modules - PuppetConf 2014
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Synapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephpSynapseindia reviews sharing intro cakephp
Synapseindia reviews sharing intro cakephp
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 

More from Patiento Del Mar

hibernateormoverview-140501154227-phpapp02.pdf
hibernateormoverview-140501154227-phpapp02.pdfhibernateormoverview-140501154227-phpapp02.pdf
hibernateormoverview-140501154227-phpapp02.pdfPatiento Del Mar
 
hibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfhibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfPatiento Del Mar
 
Spring Data Advanced Querying.ppt
Spring Data Advanced Querying.pptSpring Data Advanced Querying.ppt
Spring Data Advanced Querying.pptPatiento Del Mar
 
11-Concurrence-Section critiques.pdf
11-Concurrence-Section critiques.pdf11-Concurrence-Section critiques.pdf
11-Concurrence-Section critiques.pdfPatiento Del Mar
 
16-Concurrence-APIs-Concurrentes.pdf
16-Concurrence-APIs-Concurrentes.pdf16-Concurrence-APIs-Concurrentes.pdf
16-Concurrence-APIs-Concurrentes.pdfPatiento Del Mar
 
12-Concurrence-Rendez-vous.pdf
12-Concurrence-Rendez-vous.pdf12-Concurrence-Rendez-vous.pdf
12-Concurrence-Rendez-vous.pdfPatiento Del Mar
 
17-Concurrence-Fork-Join.pdf
17-Concurrence-Fork-Join.pdf17-Concurrence-Fork-Join.pdf
17-Concurrence-Fork-Join.pdfPatiento Del Mar
 
13-Concurrence-Producteur-consommateur.pdf
13-Concurrence-Producteur-consommateur.pdf13-Concurrence-Producteur-consommateur.pdf
13-Concurrence-Producteur-consommateur.pdfPatiento Del Mar
 
15-Concurrence-Operations-Atomiques.pdf
15-Concurrence-Operations-Atomiques.pdf15-Concurrence-Operations-Atomiques.pdf
15-Concurrence-Operations-Atomiques.pdfPatiento Del Mar
 
Concurrence-Interruption-Exceptions.pdf
Concurrence-Interruption-Exceptions.pdfConcurrence-Interruption-Exceptions.pdf
Concurrence-Interruption-Exceptions.pdfPatiento Del Mar
 

More from Patiento Del Mar (20)

grpc_tutorial.pdf
grpc_tutorial.pdfgrpc_tutorial.pdf
grpc_tutorial.pdf
 
0.coursGitEclipse.pdf
0.coursGitEclipse.pdf0.coursGitEclipse.pdf
0.coursGitEclipse.pdf
 
Primefaces.ppt
Primefaces.pptPrimefaces.ppt
Primefaces.ppt
 
hibernateormoverview-140501154227-phpapp02.pdf
hibernateormoverview-140501154227-phpapp02.pdfhibernateormoverview-140501154227-phpapp02.pdf
hibernateormoverview-140501154227-phpapp02.pdf
 
hibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdfhibernateormfeatures-140223193044-phpapp02.pdf
hibernateormfeatures-140223193044-phpapp02.pdf
 
Spring Data Advanced Querying.ppt
Spring Data Advanced Querying.pptSpring Data Advanced Querying.ppt
Spring Data Advanced Querying.ppt
 
Spring Security.ppt
Spring Security.pptSpring Security.ppt
Spring Security.ppt
 
momjms.pdf
momjms.pdfmomjms.pdf
momjms.pdf
 
rmi.pdf
rmi.pdfrmi.pdf
rmi.pdf
 
synchronization.pdf
synchronization.pdfsynchronization.pdf
synchronization.pdf
 
cours6.pdf
cours6.pdfcours6.pdf
cours6.pdf
 
java_PAR.pdf
java_PAR.pdfjava_PAR.pdf
java_PAR.pdf
 
11-Concurrence-Section critiques.pdf
11-Concurrence-Section critiques.pdf11-Concurrence-Section critiques.pdf
11-Concurrence-Section critiques.pdf
 
22-reflection.pdf
22-reflection.pdf22-reflection.pdf
22-reflection.pdf
 
16-Concurrence-APIs-Concurrentes.pdf
16-Concurrence-APIs-Concurrentes.pdf16-Concurrence-APIs-Concurrentes.pdf
16-Concurrence-APIs-Concurrentes.pdf
 
12-Concurrence-Rendez-vous.pdf
12-Concurrence-Rendez-vous.pdf12-Concurrence-Rendez-vous.pdf
12-Concurrence-Rendez-vous.pdf
 
17-Concurrence-Fork-Join.pdf
17-Concurrence-Fork-Join.pdf17-Concurrence-Fork-Join.pdf
17-Concurrence-Fork-Join.pdf
 
13-Concurrence-Producteur-consommateur.pdf
13-Concurrence-Producteur-consommateur.pdf13-Concurrence-Producteur-consommateur.pdf
13-Concurrence-Producteur-consommateur.pdf
 
15-Concurrence-Operations-Atomiques.pdf
15-Concurrence-Operations-Atomiques.pdf15-Concurrence-Operations-Atomiques.pdf
15-Concurrence-Operations-Atomiques.pdf
 
Concurrence-Interruption-Exceptions.pdf
Concurrence-Interruption-Exceptions.pdfConcurrence-Interruption-Exceptions.pdf
Concurrence-Interruption-Exceptions.pdf
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

Thymeleaf and Spring Controllers.ppt

  • 1. Spring Essentials Thymeleaf and Spring Controllers SoftUni Team Technical Trainers Software University http://softuni.bg
  • 2. Table of Contents 1. Thymeleaf  Standard Expressions  Forms  Conditionals  Loops 2. Spring Controllers 2
  • 5. 5  Thymeleaf is a view engine used in Spring  It allows us to:  Use variables/collections in our views  Execute operations on our variables "Thymeleaf is very, very extensible, and it allows you to define your own sets of template attributes (or even tags) with the names you want, evaluating the expressions you want in the syntax you want and applying the logic you want. It’s more like a template engine framework." - thymeleaf.org What is Thymeleaf?
  • 6. 6  Use Spring Initializr to import Thymeleaf, or use this dependency in your pom.xml:  Define the Thymeleaf library in your html file: How to use Thymeleaf? <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
  • 7. 7  You also need to change the Thymeleaf version in your pom.xml: Change Thymeleaf Version <properties> <thymeleaf.version> 3.0.2.RELEASE </thymeleaf.version> <thymeleaf-layout-dialect.version> 2.2.0 </thymeleaf-layout-dialect.version> </properties>
  • 8.  All Thymeleaf tags and attributes begin with th: by default  Example of Thymeleaf attribute:  Example of Thymeleaf tag(element processor):  th:block is an attribute container that disappears in the HTML 8 Thymeleaf Tags and Attributes <p th:text="Example"></p> <th:block> ... </th:block>
  • 9. 9  Variable Expressions  Selection Expressions  Link (URL) Expressions  Fragment Expressions Thymeleaf Standard Expressions ${...} @{...} *{...} ~{...}
  • 10. 10  Variable Expressions are executed on the context variables  Examples: Thymeleaf Variable Expressions ${...} ${session.user.name} ${title} ${game.id}
  • 11. 11  Selection Expressions are executed on the previously selected object  Example: Thymeleaf Selection Expressions *{...} <div th:object="${book}"> ... <span th:text="*{title}">...</span> //equivalent to ${book.title} ... </div>
  • 12. 12  Link Expressions are used to build URLs  Example:  You can also pass query string parameters:  Create dynamic URLs Thymeleaf Link Expressions @{...} <a th:href="@{/register}">Register</a> <a th:href="@{/details(id=${game.id})}">Details</a> <a th:href="@{/games/{id}/edit(id=${game.id})}">Edit</a>
  • 13. 13  Variables in Thymeleaf are defined using the following attribute:  Where 'var' is the name of our variable and 'pesho' it’s the value  Variables exists only in the scope of the tag Variables in Thymeleaf th:with="var = 'pesho'" <div th:with="name = ${user.name}"> <p th:text="${name}"> // valid </div> <p th:text="${name}"> // invalid
  • 14. 14  Fragment Expressions are easy way to move around templates  Example: Thymeleaf Fragment Expressions ~{...} <div th:with="frag=~{footer :: #main}"> … <p th:insert="${frag}"> … </div>
  • 15. 15  Including entire file  Including only a fragment  Including fragment with parameter  You can also use th:replace in order to replace the entire element Thymeleaf Fragments th:insert="~{fragments/header}" th:insert="~{fragments/header :: dark}" th:insert="~{fragments/header (theme='dark')}"
  • 16. 16  In Thymeleaf you can create almost normal HTML forms:  You can have a controller that will accept an object of given type: Forms in Thymeleaf <form th:action="@{/user}" th:method="post"> <input type="number" name="id"/> <input type="text" name="name"/> <input type="submit"/> </form> @PostMapping("/user") public ModelAndView register(@ModelAttribute User user) { ... }
  • 17. 17  You can pass objects to forms in order to use validations:  The th:field attribute creates different attributes based on the input type Forms in Thymeleaf (2) <form th:action="@{/user}" th:method="post" th:object=${user}> <input type="number" th:field="*{id}"/> <input type="text" th:field="*{name}"/> <input type="submit"/> </form>
  • 18. 18  If statements can be created in the following way:  You can create inverted if statements using th:unless: Conditional Statements in Thymeleaf <div th:if="${…}"> <p>The statement is true</p> </div> <div th:unless="${…}"> <p>The statement is false</p> </div>
  • 19. 19  You can also create switch in which the default case is "*":  Or use ternary operator: Conditional Statements in Thymeleaf (2) <div th:switch="${writer.role}"> <p th:case="'ADMIN'">The user is admin</p> <p th:case="'MOD'">The user is moderator</p> <p th:case="*">The user has no privileges</p> </div> <p th:text="${row.even} ? 'even' : 'odd'"> ... </p>
  • 20. 20  Creating a for loop:  Example: Loops in Thymeleaf <div th:each="element : ${#numbers.sequence(start, end, step)}"> <p th:text="${element}"></p> </div> <div th:each="element : ${#numbers.sequence(1, 5)}"> <p th:text="${element}"></p> </div> // 1 2 3 4 5
  • 21. 21  Creating a for-each loop:  Getting the iterator: Loops in Thymeleaf (2) <div th:each="book : ${books}"> <p th:text="*{author}"></p> </div> <div th:each="u, iter : ${users}" th:object="${u}"> <p th:text="|ID: *{id}, Username: *{name}|"></p> <p th:text="|${iter.index} of ${iter.size}|"></p> </div>
  • 23. 23  Defined with the @Controller annotation:  Controllers can contain multiple actions on different routes. Spring Controllers @Controller public class HomeController { … }
  • 24. 24  Annotated with with @RequestMapping(…)  Or Controller Actions @RequestMapping("/home") public String home() { return "home-view"; } @RequestMapping("/home") public ModelAndView home(ModelAndView mav) { mav.setViewName("home-view"); return mav; }
  • 25. 25  Problem when using @RequestMapping is that it accepts all types of request methods (get, post, put, delete, head, patch…)  Execute only on GET requests : Request Mapping @RequestMapping(value="/home", method=RequestMethod.GET) public String home() { return "home-view"; }
  • 26. 26  Easier way to create route for a GET request:  This is alias for RequestMapping with method GET Get Mapping @GetMapping("/home") public String home() { return "home-view"; }
  • 27. 27  Similar to the GetMapping there is also an alias for RequestMapping with method POST:  Similar annotations exist for all other types of request methods Post Mapping @PostMapping("/register") public String register() { … }
  • 28. 28  You can set all actions in a controller to start with a given routing:  Calling the adminPanel() will be done on route "/admin/" Controller Routing @Controller @RequestMapping("/admin") public class AdminController { @GetMapping("/") public String adminPanel() { … } }
  • 29. 29  Passing a string to the view:  The Model object will be automatically passed to the view as context variables and the attributes can be accessed from Thymeleaf using the Expression syntax - Passing Attributes to View @GetMapping("/") public String welcome(Model model) { model.addAttribute("name", "Pesho"); return "welcome"; } ${name}
  • 30. 30  The session will be injected from the IoC container when called:  Later the session attributes can be accessed from Thymeleaf using the expression syntax and the #session object: Working with the Session @GetMapping("/") public String home(HttpSession httpSession) { … httpSession.setAttribute("id", 2); … } ${session.id}
  • 31. 31  In order to set a cookie, we need to access the HttpResponse: Setting a Cookie @GetMapping("/darktheme") public String darkTheme(HttpServletResponse httpResponse) { … httpResponse.addCookie("theme", "dark"); … }
  • 32. 32  Accessing a cookie, you've set previously:  Setting a default value Getting a Cookie public String index(@CookieValue("theme") String theme) { … } public String index(@CookieValue(value = "theme", defaultValue = "bootstrap.min.css") String theme ) { … }
  • 33. 33  Accessing the HttpRequest:  Accessing all cookies: Http Request public String index(HttpServletRequest httpRequest) { … } public String index(HttpServletRequest httpRequest) { Cookie[] cookies = httpRequest.getCookies(); … }
  • 34. 34  Getting a parameter from the query string:  @RequestParam can also be used to get POST parameters Request Parameters @GetMapping("/details") public String details(@RequestParam("id") Long id) { … } @PostMapping("/register") public String register(@RequestParam("name") String name) { … }
  • 35. 35  Getting a parameter from the query string:  Making parameter optional: Request Parameters with Default Value @GetMapping("/comment") public String comment(@RequestParam(name="author", defaultValue = "Annonymous") String author) { … } @GetMapping("/search") public String search(@RequestParam(name="sort", required = false) String sort) { … }
  • 36. 36  Spring will automatically try to fill objects with a form data  The input field names must be the same as the object field names Form Objects @PostMapping("/register") public String register(@ModelAttribute UserDTO userDto) { … }
  • 37. 37  Redirecting after POST request: Redirecting @PostMapping("/register") public String register(@ModelAttribute UserDTO userDto) { … return "redirect:/login"; }
  • 38. 38  Redirecting with query string parameters Redirecting with Parameters @PostMapping("/register") public String register(@ModelAttribute UserDTO userDto, RedirectAttributes redirectAttributes) { redirectAttributes.addAttribute("errorId", 3); return "redirect:/login"; }
  • 39. 39  Keeping objects after redirect Redirecting with Attributes @PostMapping("/register") public String register(@ModelAttribute UserDTO userDto, RedirectAttributes redirectAttributes) { … redirectAttributes.addFlashAttribute("userDto", userDto); return "redirect:/register"; }
  • 40. 40  Thymeleaf is a powerful view engine  You can work with variables and helper objects  You can create loops and conditional statements  You can easily create forms  The Spring controllers have built-in IoC container  You can create routings on actions and controllers  You have access to the HttpRequest, HttpResponse, HttpSession, Cookies and others  You can redirect between actions Summary
  • 42. License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license 42
  • 43. Trainings @ Software University (SoftUni)  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University Foundation  softuni.org  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg

Editor's Notes

  1. http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html
  2. More on the standard dialect here - http://www.thymeleaf.org/doc/articles/standarddialect5minutes.html