You are on page 1of 32

Spring Web MVC –

Thymeleaf and Pagination


Sami Bhiri
Outline
1. Launching a spring boot project
2. Setting up the Business and DAO layers
3. Setting up the Web layer
4. First example to find and display all teams
5. Add pagination to the displayed list
6. Second example to find teams by names

May 20 2
Hands on Step by Step
1. Launching a spring boot project
1. information to be given
2. Dependencies to be added
3. Defining file application.properties
2. Setting up the Business and DAO layers
3. Setting up the Web layer
4. First example to find and display all teams
5. Add pagination to the displayed list
6. Second example to find teams by names

May 20 3
Launching a new spring boot
project

May 20 4
Information to be given
• Name : spring_mvc
• Group : org.horizonefele
• Artifact : spring_mvc
• Version : the one given by default
• Dependencies to choose :
• Spring Data Jpa
• MySQL Driver
• Spring Web
• Thymeleaf template engine

May 20 5
Spring boot configuration file :
application.properties
spring.datasource.url = jdbc:mysql://localhost:3308/db_teams?
useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTime
zone=UTC
spring.datasource.username = root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.show-sql= true
spring.jpa.hibernate.ddl-auto= create
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.thymeleaf.cache=false
#spring.main.banner-mode=off
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
#server.port: 8088

May 20 6
Hands on Step by Step
1. Launching a spring boot project
2. Setting up the Business and DAO layers
1. Defining the class Team
2. Defining the interface TeamRepository
3. Defining the main method
4. Execute and check
3. Setting up the Web layer
4. First example to find and display all teams
5. Add pagination to the displayed list
6. Second example to find teams by names

May 20 7
Class Team
package org.horizonefele.webMVC.entities;

import …

@Entity
public class Team implements Serializable {

@Id @GeneratedValue
private Long idTeam;

@Column(length=100)
private String name;

private Float budget;

// Getters and setters

//Constructors }
May 20 8
Interface TeamRepository
package org.horizonefele.webMVC.dao;

import java.util.List;

import …

public interface TeamRepository extends JpaRepository <Team, Long> {

May 20 9
Main method
package org.horizonefele.webMVC;

import …
@SpringBootApplication
public class WebMvcApplication {

public static void main(String[] args) {

ApplicationContext ctx = SpringApplication.run(WebMvcApplication.class, args);

TeamRepository teamDao = ctx.getBean(TeamRepository.class);

teamDao.save(new Team("Avenir Sportif de Lala", new Float(45000)));


teamDao.save(new Team("Club Olympique de Transport", new Float(60000)));
teamDao.save(new Team("Stir Sportif Jarzouna", new Float(40000)));

/* Adding other teams */


teamDao.findAll().forEach(t->System.out.println(t.getName())); }}
May 20 10
Main method

/* Adding other teams */


teamDao.save(new Team("Avenir Sportif de La Marsa", new Float(85000)));
teamDao.save(new Team("Club Africain", new Float(600000)));
teamDao.save(new Team("Club Athletique de Bizerte", new Float(440000)));
teamDao.save(new Team("Espoir Sportif de Hammem Sousse", new Float(50000)));
teamDao.save(new Team("Transport Sportif de Tunis", new Float(60000)));
teamDao.save(new Team("Espérance Sportive de Tunis", new Float(940000)));

May 20 11
Hands on Step by
1. Launching a spring boot project
2. Setting up the Business and DAO layers
3. Setting up the Web layer
1. Defining the class TeamController
2. Defining the view myTeams.jsp
2. Defining the Thymeleafe view myTeams.html
3. Execute and check
4. First example to find and dsiplay all teams
5. Add pagination to the displayed list
6. Second example to find teams by names

May 20 12
Class TeamController
package org.horizonefele.webMVC.web;

import …

@Controller
public class TeamController {

@Autowired
private TeamRepository teamDao;

@RequestMapping(value="/teams/search“, method = RequestMethod.GET)


public String search(Model model) {

model.addAttribute("message", "Hello Thymeleaf");

return "myteams";
} }

May 20 13
View myteams.html
• Thymeleaf templates to be put under : resources/templates

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<h1 th:text = "${ message }"> </h1>
</body>
</html>

May 20 14
Outline of Hands on Step by Step
1. Launching a spring boot project
2. Setting up the Business and DAO layers
3. Setting up the Web layer
4. First example to find and dsiplay all teams
1. Update the class TeamController
2. Update the view myTeams.jsp
2. Update the view myTeams.html
3. Define the file style.css
3. Use the Bootstrap library
4. Eexecute and check
5. Add pagination to the displayed list
6. Second example to find teams by names

May 20 15
Class TeamController : finding all teams
package org.horizonefele.webMVC.web;

import …

@Controller
public class TeamController {

@Autowired
private TeamRepository teamDao;

@RequestMapping(value="/teams/search")
public String search(Model model) {

List<Team> teams = teamDao.findAll();

model.addAttribute("teams",teams);

return "myteams";
} }
May 20 16
Thymeleaf view myTeams.html
<!DOCTYPE>
<html xmlns:th="http://www.thymeleaf.org"/>

<head> <meta charset="utf-8"/> <title>Teams Management</title> </head>

<body>
<h1> With Thymeleaf </h1>
<table>
<thead>
<tr> <th>REF</th><th>Name</th><th>Budget</th> </tr>
</thead>

<tr th:each="t:${teams}">
<td th:text="${t.idTeam}"></td>
<td th:text="${t.name}"></td>
<td th:text="${t.budget}"></td>
</tr>
</table> </body> </html>

May 20 17
Using the Bootstrap library
<!DOCTYPE>
<html xmlns:th="http://www.thymeleaf.org"/>

<head> <meta charset="utf-8"/> <title>Teams Management</title>


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script></head>
<body>
<h1> With Thymeleaf </h1>
<div class=container><table class="table table-striped">
<thead>
<tr> <th>REF</th><th>Name</th><th>Budget</th> </tr>
</thead>

<tr th:each="t:${teams}">
<td th:text="${t.idTeam}"></td>
<td th:text="${t.name}"></td>
<td th:text="${t.budget}"></td>
</tr>
</div></table> </body> </html>
May 20 18
Hands on Step by Step
1. Launching a spring boot project
2. Setting up the Business and DAO layers
3. Setting up the Web layer
4. First example to find and dsiplay all teams
5. Add pagination to the displayed list
1. Update the action controller
2. Update the Thymeleaf view
6. Second example to find teams by names

May 20 19
Class TeamController : adding pagination
@RequestMapping(value="/teams/search")
public String search(Model model,
@RequestParam(name="page", defaultValue="0")int page,
@RequestParam(name="size", defaultValue="5")int size) {

Page<Team> teams = teamDao.findAll(PageRequest.of(page,size) );

int[] pages = new int[teams.getTotalPages()];

model.addAttribute("teams",teams.getContent());

model.addAttribute("pages", pages);
model.addAttribute("pageCourante", page);

return “myTeams"; }

May 20 20
Thymeleaf view : adding pagination

<div class="container">
<ul class="pagination">
<li th:class="${pageCourante}==${status.index}?'active':''" th:each="p,status:${pages}">
<a th:href="@{/teams/search(page=${status.index}, motCle=${motC})}" th:text="$
{status.index}"></a>
</li>
</ul>
</div>

May 20 21
Hands on Step by Step
1. Launching a spring boot project
2. Setting up the Business and DAO layers
3. Setting up the Web layer
4. First example to find and dsiplay all teams
5. Add pagination to the displayed list
6. Second example to find teams by names
1. Update interface TeamRepository
2. Update class TeamController
3. Update view myTeams.jsp
4. Update view myTeams.html
5. Execute and check

May 20 22
Interface TeamRepository for finding
teams by names with pagination
package org.horizonefele.dao;

import …

public interface TeamRepository extends JpaRepository <Team, Long> {

@Query("select t from Team t where t.name like :x")


public Page<Team> findByName(@Param("x")String mc, Pageable pg);

May 20 23
Class TeamController for finding teams by
names with pagination
@RequestMapping(value="/teams/search")
public String search(Model model, @RequestParam(name="motCle", defaultValue="")String
mc, @RequestParam(name="page", defaultValue="0")int page,
@RequestParam(name="size", defaultValue="5")int size) {

Page<Team> teams = teamDao.findByName("%"+mc+"%",PageRequest.of(page,size) );

int[] pages = new int[teams.getTotalPages()];

model.addAttribute("teams",teams.getContent());
model.addAttribute("motC",mc);

model.addAttribute("pages", pages);
model.addAttribute("pageCourante", page);

return "myTeams"; }
May 20 24
Thymeleaf View myteams.html for finding
teams by names.
<h1> With Thymeleaf </h1>

<div class=container>
<form action="/teams/search" method="post"> <table> <tr>
<td>Mot Clé: </td>
<td> <input type="text" name="motCle" th:value="${motC}"/></td>
<td><input type="submit" name="action" value="search" /> </td>
</tr> </table> </form>

</div>

May 20 25
More actions to be implemented

1. Add one team


2. Delete an existing team
1. Update view myTeams.html
2. Update class TeamController
3. Edit and update an existing team

May 20 26
Update view myTeams.html
<tr th:each="t:${teams}">
<td th:text="${t.idTeam}"></td><td th:text="${t.name}"></td><td th:text="${t.budget}"></td>
</tr>

<tr th:each="t:${teams}">
<td th:text="${t.idTeam}"></td><td th:text="${t.name}"></td><td th:text="${t.budget}"></td>
<td> <a onclick="return confirm('Please Confirm')"
th:href="@{/teams/delete(ref=${t.idTeam}, mc=${motC})}"> Delete </a> </td>
</tr>

May 20 27
Update class TeamController

@RequestMapping(value="/teams/delete")
public String delete(Model model,
@RequestParam(name="ref", defaultValue="")Long idTeam,
@RequestParam(name="mc", defaultValue="")String mc) {

teamDao.deleteById(idTeam);
return "redirect:/teams/search?motCle="+mc;
}

May 20 28
More actions to be implemented

1. Add one team


2. Delete an existing team
3. Edit and update an existing team
1. Update view myTeams.html
2. Update class TeamController
3. Add view editTeam

May 20 29
Update view myTeams.html
<tr th:each="t:${teams}">
<td th:text="${t.idTeam}"></td><td th:text="${t.name}"></td><td
th:text="${t.budget}"></td>
<td> <a onclick="return confirm('Please Confirm')"
th:href="@{/teams/delete(ref=${t.idTeam}, mc=${motC})}"> Delete </a> </td>
</tr>

<tr th:each="t:${teams}">
<td th:text="${t.idTeam}"></td>
<td th:text="${t.name}"></td>
<td th:text="${t.budget}"></td>
<td> <a onclick="return confirm('Please Confirm')"
th:href="@{/teams/delete(ref=${t.idTeam}, mc=${motC})}"> Delete </a> </td>
<td> <a th:href="@{/teams/edit(ref=${t.idTeam}, name=${t.name}, budget=${t.budget},
edit=0, mc=${motC})}">Edit</a> </td>
</tr>
May 20 30
Update class TeamController
@RequestMapping(value="/teams/edit")
public String edit(Model model,
@RequestParam(name="ref", defaultValue="")Long idTeam,
@RequestParam(name="name", defaultValue="")String name,
@RequestParam(name="budget", defaultValue="")Float budget,
@RequestParam(name="edit", defaultValue="")int edit,
@RequestParam(name="mc", defaultValue="")String mc) {

if (edit == 0) {
model.addAttribute("idTeam", idTeam);
model.addAttribute("name", name);
model.addAttribute("budget", budget);
model.addAttribute("motCle", mc);
return "editTeam";
}
else {
Optional<Team> ot = teamDao.findById(idTeam);
Team t = ot.get();
t.setName(name);
t.setBudget(budget);
teamDao.save(t);

return "redirect:/teams/search?motCle="+mc;
} May
} 20 31
View editTeam.html
<body>
<div class="container">
<h1> Edit Team </h1> <p></p> <p></p>

<form action="/teams/edit" method="get">


<table>
<tr> <td>REF</td> <td> <input type="text" name="ref" th:value="${idTeam}"
readonly/></td> </tr>
<tr> <td>Name</td> <td> <input type="text" name="name" th:value="${name}"/></td> </tr>
<tr> <td>Budget</td> <td> <input type="text" name="budget" th:value="${budget}" /></td>
</tr>
<tr><td><input type="hidden" name="mc" th:value="${motCle}"/></td><td><input
type="hidden" name="edit" value="1"/></td></tr>

<tr><td><input type="submit" name="action" value="save"/></td></tr>

</table> </form> </div> </body>


May 20 32

You might also like