Spring Boot Web MVC
Spring Boot Web MVC
1. DispatcherServlet
2. Handler Mapper
3. Controller
4. ModelAndView
5. ViewResolver
6. View
Chapter-03
Spring Boot Web MVC
When Client sent request to our application that request received by DispatcherServlet,
It will perform pre-processing of the request (like capturing the from data/url pattern) in
java object and post-processing of the response (means sent the response to the client.
Then, DispatcherServlet will send the request to the HandlerMapper. HandlerMapper
identify which type of request is process by which controller class (In one project contain
lots of controller and controller method). Then HandlerMapper give to controller
information to the DispatcherServlet.
Then, the DispatcherServlet contact to the controller to handling the request. The
Controller execute the logic and return ModelAndView Object to the DispatcherServlet.
(Controller also called as request handler)
Model:
A model contains the data in the key-value format of the application. A data can be a
single object or a collection of objects.
View:
Represent Logical file name.
Example:
1. @GetMapping("/welcome")
2. public ModelAndView getWelcomeMsg() {
3. ModelAndView mv = new ModelAndView();
4. mv.addObject("msg", "Alhamdulillah, My First Web MVC Application");
5. mv.setViewName("message"); // pageName
6. return mv;
7. }
Then, DispatcherServlet uses ViewResolver to identify where is the presentation file (file
Location indicate prefix) and what is the presentation technique type (means file
extension like .jsp or thymeleaf or jsf indicate suffix).
Example:
In Application .properites/.yml file we define below key-value-
Chapter-03
Spring Boot Web MVC
Flow: Request- Response in Spring Boot web MVC
1. Enduser opens any one browser/client
2. Browser makes request
3. Request Goes to FC (FrontController)
4. FC connecting with HandlerMapper gives Path and HTTP Method as input.
5. Gets Controller class and method details
6. FC will call controller method (execute)
7. Controller#method will process the request
8. Controller#method returns ViewName and gives Data(Model) if present.
9. FC uses ViewResolver to find full PageName
10. ViewResolver adds prefix=Folder of UI Pages suffix = extension of UI pages
11. FC will get Full page name and executes it.
12. UI Page reads data from Model (Rendering)
13. UI Page output is given as HTML to FC.
14. FC returns HTML data as Response back to browser
15. Browser will display output.
====================
Method Return Types
====================
In Spring boot web MVC the controller class method return type as below-
ModelAndView
String
ModelAndView:
To send data from controller to view page and set the view page Name.
Sending Data using mv.addObject("msg”, “msg Description”);
And set view page name mv.setViewName(“index”)
To read data at UI using EL ${msg}
Chapter-03
Spring Boot Web MVC
String:
1. If we do not send any data to UI page and only show static data like loading form
or home page.
Example:
1. @GetMapping("/")
2. public String loadPage() {
3. return "index";
4. }
========
Model:
========
To send data from controller to View (UI), we can use Model Memory.
This is internally one Map (Model(I) Impl class). That Stores data in Key=Val
format.
Where, Key is String type, Value is Object (anything).
Spring container creates this model memory and handle it. We can just add
data using method addAttribute(key,val) and read data at UI using
Expression language(EL) ${key}.
Chapter-03
Spring Boot Web MVC
================
@ModelAttribute
================
When End-user enters data and submit the form, the form data convert into
model class object by Spring container. This Object is called as Model
Attribute. That we can read at controller.
(or)
Read data from UI form as Object.
When create and destroy?
It is created for every request and present in container until response
committed.
Syntax:
@ModelAttribute("ObjName") ClassName localVariable
@ModelAttribute("employee") Employee emp
==========================
Spring boot web MVC with JSP
==========================
Tomcat is given as Embedded Server (Default) by Spring web starter dependecy
runs at port 8080.
Tomcat has two containers
Jasper for jsp to Servlet container
CATALINA takes servlet code like compilation, object creatation, life cycle.
If we download tomcat server the servlet for CATALINA and JSP for JASPER
container by default came but embedded tomcat JASPER for JSP by default not
given. that’s why Embedded Tomcat is also called as light weight container
service. So if we work with JSP then add tomcat jasper dependency. If we do not
add this dependency then browser not view JSP pages. Only download this page.
1. <dependency>
2. <groupId>org.apache.tomcat.embed</groupId>
3. <artifactId>tomcat-embed-jasper</artifactId>
4. </dependency>
Chapter-03
Spring Boot Web MVC
========================================
First Web Application using Spring boot + JSP
========================================
Create one Spring boot application with below dependencies
Spring-web-starter
Tomcat-jasper for JSP
Create Folder System for UI Pages
Right click on src >> main folder >> new >> folder option> Enter name as
"webapp" > finish
|-src
|-main
|-webapp
|-WEB-INF
|-pages
In application.properties file
#Port number details
server.port=9090
#View Resolver details
#---prefix must starts with / and ends with /
spring.mvc.view.prefix=/WEB-INF/pages/
spring.mvc.view.suffix=.jsp
1. @Controller
2. public class UserController {
3. //@RequestMapping(value = "/home", method = RequestMethod.GET)
4. @GetMapping("/home")
5. public String showHomePage() {
6. return "UserHome";
7. }
8. }
Chapter-03
Spring Boot Web MVC
If we Got White Label Error Page?
Then check-
1. Remove spaces at properties file (if added)
2. Check Folder system
3. UI/View Page name is case-sensitive
4. Check did you add Tomcat Embedded JASPER?
5. Check BasePackage Rule for controller class. [must be in same package or
subpackage of main class]
Why JSP avoid for UI?
Jsp is called as heavyweight UI technology which occupy more memory because
finally JSP convert into Servlet and create lots of object. even if we define static
content that is converted into servlet code like
[Out.write(“<p> hello </p>”);]
============
Thymeleaf UI
============
Using HTML we can create static pages. We can’t create dynamic web page
because we can’t write java code into HTML directly.
Jsp is used to create dynamic web page. But JSP is Heavyweight and also slow.
Because JSP finally convert into the servlet.
What is Thymeleaf?
Thymeleaf UI is light weight Java UI Engine used to design Dynamic web pages in
web application/pages.
It is a simple HTML File which contains static tags[HTML tags] and Thymeleaf
Tags[dynamic tags].
Only Thymeleaf Tags are converted into Java Code => executed => place result
back to Same file (Rendering).
Chapter-03
Spring Boot Web MVC
In thymeleaf, we no need to specify prefix and suffix in .properties file. Spring
boot will identify automatically in the default location – src/main/resources/
template folder.
Example:
|-src
|-main
|-resources
|- static (for Images/CSS Files/ Java Script Files)
|- templates
|- home.html (thymeleaf)
Xmlns where ns = namespace -> a location where all tag definition exist.
===========================
Thymeleaf Expression Types
===========================
1. Variable Expression
Read object data into UI from controller (Model)
Syntax
${obj.variableName}
String interpolation - [[ ${emp.empName} ]]
Example:
<span th:text="${prodCode}"><span>
<p> This is product code [[${prodCode}]] </p>
Chapter-03
Spring Boot Web MVC
2. Link Expression
It is used for URL/Path/Location
Syntax
@{/url}
Example:
<form th:action="@{/employee/save}" method= “POST”> </form>
<script type="text/javascript" th:src="@{/myjs/sample.js}"> </script>
<img th:src="@{/images/doctor.png}"/>
3. Selection Expression
It is used to binding for form input name with model attributes or model
class variables. (Basically, used for editing, when database data load into
form input)
Syntax
*{variableName} // exactly same with model class variable name
Example:
<input type="text" th:field="*{empName}">
4. Message Expression
Bring externalized (. properties) text into our UI file.
(Or) read message/data from .properties file.
Syntax
#{textName}
==============================
Chapter-03
Spring Boot Web MVC
Thymeleaf Conditions and Iteration
==============================
1. Iteration:
Used to print Collection (List, Map, Set) data into html Table row or html
list.
Syntax
th:each= “tempVariable:${CollectionObj}”
Example:
th:each="ob:${lists}"
Here th:each is like forEach loop.
ob is tempvariable, ${} used to read data from Model
‘lists’ is keyname sent from Controller class
Example:
2. If condition
Chapter-03
Spring Boot Web MVC
Example:
th:if="${lists==null or lists.isEmpty()}"
URL-Rewriting:
Creating one URL using static path and Dynamic path is called as URL-Rewriting.
Syntax
th:href="@{/student/delete?(id=${obj.studentId})}"
(or)
th:href="@{/student/delete(id=${obj.studentId})}"
==============
Thymeleaf Form
==============
- In normal HTML form, form data will be converted into object by Spring container.
That is unidirectional we cannot convert Object into form data. (at the time of
editing user details.
- So for this requirement we use thymeleaf form that is bidirectional means form
data convert into Object and Object convert into form data.
=======
Chapter-03
Spring Boot Web MVC
redirect
=======
- It is used to redirect one controller method to another controller method using
URL mapping end point.
- Syntax:
redirect: url-end-point
================
RedirectAttributes
================
- While redirect, to pass data from one Controller method to another controller
method use RedirectAttributes. But read data as Optional Request Param.
@RequestParam(value="", required=false).
Use Case:
- While we deleting some data and after deleting data, we load latest data
with some message like “employee 101 deleted”.
Example:
#Method for fetching All Employees data
1. @GetMapping("/getAll")
2. public String getAll(@RequestParam(value="msg", required = false) String message,
3. Model model, @PageableDefault(page=0,size=4) Pageable pageable) {
4. Page<StudentEntity> page = service.getAllStudent(pageable);
5. model.addAttribute("lists",page.getContent());
6. model.addAttribute("page",page);
7. model.addAttribute("msg",message);
8. return "AllStudent";
9. }
#Method for deleting one Employee data and load latest data
1. @GetMapping("/delete")
2. public String deleteStudent(@RequestParam("id") Integer id,
Chapter-03
Spring Boot Web MVC
3. RedirectAttributes attribute,Model model) {
4. String message = null;
5. try {
6. service.deleteOneStudent(id);
7. message = new StringBuffer()
8. .append("Student ")
9. .append(id)
10. .append(" Deleted").toString();
11. }catch(StudentNotFoundException e) {
12. e.printStackTrace();
13. message = e.getMessage();
14. }
15. attribute.addAttribute("msg",message);
16. return "redirect:getAll";
17. }
Note:
- Return “redirect:all” and RedirectAttributes not depend on each other’s. if
we send some data to along with /all url controller method then use
RedirectAttributes otherwise only return “redirect:all”.
Web Application Layers:
- It is a common approach/method followed by Lot of developers.
- Testing/Maintaining (Find Errors and Fix) is easy in this case.
- In simple meaning Layer means type of work/code/method. One Layer indicates
one type of work.
To develop web application In Spring boot peoples are use Three layers
1. Presentation Layer
Implemented using Spring boot web MVC To write display logic,
request processing code. (Controller class)
2. Service Layers
To write calculations, Transaction Management also known as :
Business Layer
3. Data Access Layer:
DAL -- To Define Database operations (CRUD)
To connect Layers to each other by using Java below relations-
Chapter-03
Spring Boot Web MVC
1. In between Layers: HAS-A ( + @Autowired)
2. Within Layers: IS-A (extends/implements)
This Layers Design is used to develop application using modules concept.
Example: Amazon App
Search, Cart, Payment, Feedback, Tracking..etc (Modules)
Gmail App
User (Register, Login), Inbox, Sent ...(Modules)
Note: For each module one model class is required for a DB table.
Questions:
Chapter-03
Spring Boot Web MVC
What is Spring Web MVC?
It is one Module in Spring Framework which is follow MVC design pattern to
implement Web Applications/presentation layer.
What are the Advantages using Spring Web MVC?
What is DispatcherServlet (Front Controller)?