SPRING WEB
MVC
Viktoriya Ryazhska, 2020
Agenda
• What is MVC pattern?
• Spring MVC workflow
• Simple web application
• Thymeleaf
• Controller’s examples
Web application
Client
Request Response
Server
MVC pattern
• Model–view–controller (usually known as MVC) is a software
design pattern commonly used for developing user interfaces that
divides the related program logic into three interconnected
elements.
• This is done to separate internal representations of information
from the ways information is presented to and accepted from the
user.
• This kind of pattern is used for designing the layout of the page.
Wikipedia
Model
@Entity The Model is the central component of the
public class User { pattern. It is the application's dynamic data
structure, independent of the user interface.
@Id It directly manages the data, logic and rules
@GeneratedValue of the application
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
@NotBlank(message = "Email is mandatory")
private String email;
// standard constructors / setters / getters / toString
}
View
The View is responsible for rendering the model data and in general
it generates HTML output that the client's browser can interpret.
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>View Example</title>
<meta http-equiv="Content-Type" content="text/html />
</head>
<body>
<p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
Controller
@Controller
public class OrderController {
@PostMapping("/order")
public String createOrder(@ModelAttribute(name=“order") Order
order) {
orderService.save(order);
model.addAttribute("orders", orders);
return "redirect:/orders";
}
// other methods
}
The Controller is responsible for processing user requests and
building an appropriate model and passes it to the view for rendering.
Spring MVC
• The Spring Web MVC framework provides Model-View-Controller
(MVC) architecture and ready components that can be used to
develop flexible and loosely coupled web applications. The MVC
pattern results in separating the different aspects of the application
(input logic, business logic, and UI logic), while providing a loose
coupling between these elements.
• The Spring Web MVC Framework is a robust, flexible and well-
designed framework for rapidly developing web application using
the MVC design pattern
Main Components
• DispatcherServlet
• Controller
• HandlerMapping/@RequestMapping
• ModelAndView
• Model and @ModelAttribute
• ViewResolver
The DispatcherServlet
HTTP Request HTTP Response
DispatcherServlet
Handle
View
r Controll
Resolve View
Mappin er
r
g
Starting with Spring Initializr
Application Configuration
package com.softserve.Example;
import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
pom.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/>
</parent>
pom.xml
Add dependency to pom.xml file mvn dependency:tree
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
...
</dependencies>
index.html
<!DOCTYPE HTML>
<html>
resources/static
<head>
<title>Welcome page</title>
<meta content="text/html; charset=UTF-8"
http-equiv="Content-Type"/>
</head>
<body>
<p>Home page is <a
href="/hello">here</a></p>
</body>
</html>
View Template Libraries
• JSP/JSTL
• Thymeleaf
• Tiles
• Freemarker
• Velocity
Thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf
spring.thymeleaf.cache=true
spring.thymeleaf.enabled=true
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.application.name=Spring Boot
@Controller. Example
@Controller
public class
ControllerExample {
@GetMapping("/hello")
public String getHome() {
return "home";
}
}
@Controller. Example
@GetMapping("/users")
public String getUsers(Model model) {
model.addAttribute("users", users);
return "users";
} фрагмент якої зображений на екрані
@Controller. Example
<h2>List of users</h2>
<table>
<tr>
<th>Lastname</th> <th>Firstname</th> <th></th>
</tr>
<tr th:each="user: ${users}">
<td th:text="${user.lastName}" />
<td th:text="${user.fisrtName}" />
<td>
<a th:href="@{/delete/{userId}(id=${user.id})}"> Remove
</a>
</td>
</tr>
</table>
@Controller. Example
@DeleteMapping("/delete/{userId}")
public String
deleteUser(@PathVariable(name="userId") Integer id) {
users.remove(users.get(id));
return "redirect:/users";
}
@Controller. Example
<h1>Add User</h1>
<form th:action="@{/saveUser}" th:object="${user}" method="post">
<p>Firstname: <input type="text" th:field="*{fisrtName}"/></p>
<p>Lastname: <input type="text" th:field="*{lastName}"/></p>
<p><input type="submit" value="Add user"/></p>
</form>
@Controller. Example
@PostMapping("/saveUser")
public String addUser(@ModelAttribute(name="user") User user) {
userService.save(user);
users.add(user);
return "redirect:/users";
}
@Controller. Example
@GetMapping("/user/{id}")
public String setUserName( @PathVariable(name="id") Integer id
@RequestParam(name="name", required=true,
defaultValue=“unknown”) String lastName, Model model) {
User user = userService.findById(id);
user.setFirstName(firstName);
model.addAttribute("user", user);
return "home";
}
/user/15?
Validation
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotBlank(message = "Name is mandatory")
private String name;
// standard constructors / setters / getters / toString
}
Validation
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId
>
</dependency>
Validation
@PutMapping("/update/{id}")
public String getUser(@PathVariable(name="id") Integer id,
@Valid @RequestBody User user) {
User userDB = userService.findById(id);
// update userDB to user;
userService.save(userDB);
return "redirect:/users";
}
References
• https://spring.io/projects/spring-boot
• https://www.baeldung.com/spring-boot-start
• https://spring.io/guides/gs/serving-web-content/
• https://
www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#integrating-thymelea
f-with-spring
• https://www.tutorialspoint.com/spring_boot/spring_boot_thymeleaf.htm
• https://www.baeldung.com/spring-request-param
SoftServe Confidential