Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
195 views

Spring Boot Web MVC

The document discusses Spring Boot Web MVC including its architecture, components like DispatcherServlet and ViewResolver, and how requests are handled. It also covers returning data from controllers to views using ModelAndView and the Model, and using JSP and Thymeleaf as view technologies.

Uploaded by

Java Pro
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
195 views

Spring Boot Web MVC

The document discusses Spring Boot Web MVC including its architecture, components like DispatcherServlet and ViewResolver, and how requests are handled. It also covers returning data from controllers to views using ModelAndView and the Model, and using JSP and Thymeleaf as view technologies.

Uploaded by

Java Pro
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Chapter-03

Spring Boot Web MVC


MVC:
 It is a Design Pattern to develop a web application/Presentation layer.
 M= Model (Data)
 V = View (Presentation/UI technology)
 C = Controller (Class/request processing code)

Spring Web MVC:


 It is one Module in Spring Framework to implement Web Applications using any
UI (Java UI means JSP, Thyme leaf, Velocity, JSF,...etc).
 Spring Boot Web MVC module simplified web application development process.
 Form Binding (form <---> java obj )
 Flexibility in Form Binding (type conversion)
 Multiple Presentation Technologies (JSP & Thymeleaf)
 Form Tag Library (ready-made tags support).

Spring Web MVC Architecture:

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. }

2. If we send data to UI page using Model(I).


 Example:
1. // send object to UI page
2. @RequestMapping(value = "/send", method = RequestMethod.GET)
3. public String sendObj(Model model) {
4. Employee employee = new Employee(101, "Nadim", "nadim26@gmail.com");
6. model.addAttribute("emp", employee);
7. return "welcome";
8. }

========
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

 @ModelAttribute ClassName ObjName


@ModelAttribute Employee employee

==========================
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

 Create JSP file under pages folder.


 Right click on pages folder > new > File Option > Enter name. ex:
UserHome.jsp.

 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

 Create Controller class

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.

 To overcome above problems, we are using Thymeleaf in HTML.

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)

How to config Thymeleaf in html file?


 If we want to use thymeleaf we to define thymeleaf server location url in
html tag.
 Example:
<html xmlns:th = “www.thymeleaf.org” > . . . . . </html>

 https://www.thymeleaf.org/ is a server/namespace [location of tag


definition] which gives all pre-defined tags/attributes.

 Prefix "th", indicates Thymeleaf Tags/attributes, only those are processed by


Thymeleaf Engine.

 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:

<table class="table table-hover">


<tr class="bg-primary text-white">
<th>ID</th>
<th>NAME</th>
<th>AUTHOR</th>
<th>COST</th>
<th>OPERATIONS</th>
</tr>
<tr th:each="ob:${list}">
<td th:text="${ob.bookId}"></td>
<td th:text="${ob.bookName}"></td>
<td>[[${ob.bookAuth}]]</td>
<td>[[${ob.bookCost}]]</td>
<td>
<button class="btn btn-danger">DELETE</button> |
<button class="btn btn-info">EDIT</button>
</td>
</tr>
</table>

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.

<form th:action= “${url}” method= “POST” th:object="${employee}">


<input type="text" th:field="*{empName}"/>
<input type="text" th:field="*{empSal}"/>
</form>

=======
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)?

 Dispatcher Servlet (FrontController) is a pre-defined Servlet. It will dispatch


(send/transfer) request b/w multiple components. (Or) Responsible to perform
Pre-Processing and Post-Processing of request.
 In Spring F/w we need to configure using web.xml, But in Spring boot it is Auto-
Configured.
Pre-processing:
 Before processing the request, it will capture the data or url and binding to the
java object.
Post-Processing:
 Whatever response is available send the response to the client.
What is Controller?
 Controller is a java class that define by the programmer which is execute the logic
or processing the request and return ModelAndView Object as response. Where
Model is a data in key-value format and View Name which has no location and
extension details. To be independent of UI Technologies.
Why HandlerMapper is used in Spring WEB MVC?
 It is a map internally. It holds all controller method details and help to identify
which request is processing by which controller class/method.
 Like For which request/path/URL , where to Go.
What is View Resolver?
 It helps to find view Page by adding file location and file extension.
(or)
It is identified where is the presentation file location and what is the presentation
technique (means .jsp or thymeleaf etc.)
 In Spring F/w we need to define one <bean> for ViewResolver. In Spring Boot, it is
autoconfigured. Just pass prefix and suffix using properties/yaml file.
Chapter-03
Spring Boot Web MVC
 ---Example--------------
 spring.mvc.view.prefix=/WEB-INF/mypages/
 spring.mvc.view.suffix=.jsp
what is viewPage?
 It will display final result to End-user inside a Browser. Our View Page will be
executed and output is given as: HTML (CSS, JS) returned back to FC.
 ViewPage = Prefix + ViewName + Suffix
/folderName/ Inbox .jsp
In how many ways browser can make request?
 Three ways browser to make request
 Enter URL in Addressbar (GET)
 HTML Form Submit (GET/POST)
 Click on HyperLink (<a>) (GET)
What is Controller class?
 Controller is a class, that contains request processing methods. For every module
we define one controller.
What is Expression Language?
 It is used to read data from Model(memory).
 Syntax: ${keyName}.
 At runtime all expressions are replaced with their data taken from Model is called
as Rendering.
Which option we need to choose for Web Application Packaging?
 We can use JAR if we want to work with embedded Server. For external
Deployment use: WAR option only.
What is Port Number?
 A Logical number assigned by OS, to identify a unique service.
 At a time two different services cannot use same port number.
 0-1024 are called as reserved port numbers.
 Http - 80, https-443.
Why we need to add @Controller over class insted of @Component?
Chapter-03
Spring Boot Web MVC
 @Component will inform container to create object. It will not support any HTTP
Operations.
 @Controller in simple creating object + HTTP Protocol support.
Who will call or execute controller method and when?
 FrontController/DispatcherServlet will call/execute our method when request
comes. for 1 request -- 1 method call. Container creates object only once.
How can we map/link one java method with Request Details(PATH/HttpMethod)?
 We can use annotation @RequestMapping() or Specific annotations like
@GetMapping @PostMapping ..etc.

Q) Can't we use only POST for all Types of Operations?


 Yes, We can. But Http has set universal rules for providers/consumers to access
services over internet.

You might also like