Spring Web MVC

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 43

Spring Web MVC

Sami Bhiri
Spring Web MVC : what is it?
• Spring framework module that
• simplifies the creation of web applications server side
• follows and implements the MVC pattern
• hides the (complex) use of the JEE Servlet API thanks to several annotations
• can be used for developing REST services.

• Like other spring modules,


• it relies on dependency injection
• can be used with other modules especially spring data with JPA.

May 20 2
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5
View Model Controller
4
DAO Layer
9 7 6 2

1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 3
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5
View Model Controller
The front controller 4
intercepts all DAO Layer
client's HTTP 9 7 6 2
requests

1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 4
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5
View Model Controller
4
Then the front
DAO Layer
controller routes the
9 7 6 2 request to the
appropriate controller.
1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 5
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5
View Model Controller
4
DAO
The controller
Layer
9 7 6 2 interacts with the
business and/or DAO
layer.
1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 6
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5
View Model Controller
4
The controller builds DAO Layer
9 7 and populate a model 6 2
with the data to be
displayed / returned
1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 7
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5
View Model Controller
and returns the 4
name of the DAO Layer
9 7 corresponding view 6 2
to be returned to the
client.
1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 8
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5
View Model Controller
The front controller 4
transmits the model DAO Layer
9 7 to the view which 6 2
returns the
response.
1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 9
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5
View Model Controller
4
DAO Layer
9 7 6 2
The front controller
returns back
1 the
response generated
Web HTTP Request
by the View. Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 10
Spring Web MVC : Architecture
Web Layer Business
3 Layer
8 5The last session, we
View Model Controller
covered the business
4
and DAO layers.
DAO Layer
9 7 6 2

1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 11
Spring Web MVC : Architecture
Web Layer Business
In this session, we will 3 Layer
8 5
cover the Web layer to View Model Controller
build a simple web 4
application server side. DAO Layer
9 7 6 2

1
Web HTTP Request
Front Controller DBMS
Client DispatcherServlet
10
HTTP Response
May 20 12
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 dsiplay all teams
5. Second example to find teams by names

May 20 13
Launching a new spring boot
project

May 20 14
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

May 20 15
16
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.main.banner-mode=off
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
#server.port: 8088

May 20 17
Dependencies to be added to pom.xml
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
May 20 18
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 dsiplay all teams
5. Second example to find teams by names

May 20 19
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 20
Interface TeamRepository
package org.horizonefele.webMVC.dao;

import java.util.List;

import …

public interface TeamRepository extends JpaRepository <Team, Long> {

May 20 21
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 22
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
1. Defining the class TeamController
2. Defining the view myTeams.jsp
3. Execute and check
4. First example to find and dsiplay all teams
5. Second example to find teams by names

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

import …

@Controller
public class TeamController {

@Autowired
private TeamRepository teamDao;

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

return "myteams";
} }

May 20 24
View myteams.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding=“utf-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<h1> Hello Web Layer </h1>
</body>
</html>

May 20 25
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
3. Define the file style.css
4. Eexecute and check
5. Second example to find teams by names

May 20 26
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 27
View myTeams.jsp : displaying all teams
<%@ page language="java" contentType="text/html"; charset="utf-8"
pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html> <head> <meta charset="utf-8"> <title>Teams Management</title>
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/style.css"/> </head>

<body> <div>
<form action="/teams/search" method="post"> <table> <tr>
<td>Mot Clé: </td>
<td> <input type="text" name="motCle" /></td>
<td><input type="submit" name="action" value="search" /> </td>
</tr> </table> </form>

<table class="tabteams"> <tr> <th>REF</th><th>Name</th><th>Budget</th> </tr>

<c:forEach items="${teams}" var="t">


<tr> <td>${t.idTeam}</td> <td>${t.name}</td> <td>${t.budget}</td> </tr>
</c:forEach>

</table> </div> </body> </html>

May 20 28
Style sheet file style.css
div {
border : 1px solid gray;
padding: 10px;
margin : 10px;
}

.tabteams th{
border : 1px solid gray;
padding: 10px;
margin : 10px;
background: lightblue;
}

.tabteams td{
border : 1px solid gray;
padding: 10px;
margin : 10px;
background: gray;
opacity: 0.8;
}
May 20 29
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. Second example to find teams by names
1. Update interface TeamRepository
2. Update class TeamController
3. Update view myTeams.jsp
4. Execute and check

May 20 30
Interface TeamRepository for finding
teams by names
package org.horizonefele.webMVC.dao;

import …

public interface TeamRepository extends JpaRepository <Team, Long> {

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


public List<Team> findByName(@Param("x")String mc);

May 20 31
Class TeamController for finding teams by
names
package org.horizonefele.webMVC.web;

import …

@Controller
public class TeamController {

@Autowired
private TeamRepository teamDao;

@RequestMapping(value="/teams/search")
public String search(Model model,@RequestParam(name="motCle", defaultValue="")String mc) {

List<Team> teams = teamDao.findByName("%"+mc+"%");

model.addAttribute("teams",teams);

return "myteams"; } }
May 20 32
View myteams.jsp for finding teams by
names.
<form action="/teams/search" method="post">
<table>
<tr>
<td>Mot Clé: </td>
<td> <input type="text" name="motCle" value="${motCle}"/></td>
<td><input type="submit" name="action" value="Search"/> </td>
</tr>
</table>
</form>

May 20 33
More actions to be implemented

1. Add one team


1. Update class TeamController
2. Add the view addTeam
2. Delete an existing team
3. Edit and update an existing team

May 20 34
Update class TeamController
@RequestMapping(value="/teams/add")
public String add(Model model, @RequestParam(name="name", defaultValue="")String name,
@RequestParam(name="budget", defaultValue="0")Float budget) {

if (!(name.equals(""))) {
model.addAttribute("name",name);
model.addAttribute("budget", budget);

Team t = new Team(name, budget);


teamDao.save(t);
}

return "addTeam";
}

May 20 35
View addTeam.jsp
<!-- Similair to myteams.jsp -->
<body>
<div>
<form action="/teams/add" method="post">
<table>
<tr><td>Name</td><td> <input type="text" name="name" /></td></tr>
<tr><td>Budget</td> <td> <input type="text" name="budget" /></td> </tr>
<tr><td> <input type="submit" name="action" value="save"/></td></tr>
</table>
</form>
</div>

</body>
</html>

May 20 36
More actions to be implemented

1. Add one team


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

May 20 37
Update view myTeams.jsp
<tr>
<td>${t.idTeam}</td><td>${t.name}</td><td>${t.budget}</td>
</tr>

<tr>
<td>${t.idTeam}</td><td>${t.name}</td><td>${t.budget}</td>
<td> <a onclick="return confirm('Please Confirm')"
href="/teams/delete?ref=${t.idTeam}&mc=${motCle}"> Delete </a> </td>
</tr>

May 20 38
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 39
More actions to be implemented

1. Add one team


2. Delete an existing team
1. Update view myTeams.jsp
2. Update class TeamController
3. Edit and update an existing team
1. Update view myTeams.jsp
2. Update class TeamController
3. Add view editTeam
May 20 40
Update view myTeams.jsp
<tr>
<td>${t.idTeam}</td><td>${t.name}</td><td>${t.budget}</td>
<td> <a onclick="return confirm('Please Confirm')"
href="/teams/delete?ref=${t.idTeam}&mc=${motCle}"> Delete </a> </td>
</tr>

<tr>
<td>${t.idTeam}</td><td>${t.name}</td><td>${t.budget}</td>

<td> <a onclick="return confirm('Please Confirm')" href="/teams/delete?ref=$


{t.idTeam}&mc=${motCle}"> Delete </a> </td>

<td> <a href="/teams/edit?ref=${t.idTeam}&name=${t.name}&budget=$


{t.budget}&edit=0&mc=${mo tCle}">Edit</a> </td>
May 20 41
</tr>
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 42
View editTeam.jsp
<!-- similar to myTeams.jsp -->

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

<table>
<tr> <td>REF</td> <td> <input type="text" name="ref" value="${idTeam}" readonly/></td> </tr>
<tr> <td>Name</td> <td> <input type="text" name="name" value="${name}"/></td> </tr>
<tr> <td>Budget</td> <td> <input type="text" name="budget" value="${budget}" /></td> </tr>
<tr><td><input type="hidden" name="mc" 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> </html>

May 20 43

You might also like