You are on page 1of 54

JpaRepository:

 It is an predefined interface provided by Spring Data


 Using this interface provided methods we can perform curd operations
 This interface provides extra methods to perform pagination and sorting
Sorting
Sort the records based column values
ex: findAll(Sort.property("empSalary"));
findAll(Sort.property("empSalary").descending());
Note: The property that we are passing is an entity class variable which is mapped to database table.

Pagination
The process of dividing total no.of records into multiple pages is called as Pagination.
Ex: Gmail inbox, Google Search Results etc...
We can implement pagination in 2 ways
 Server side pagination
 Client Side pagination

Server Side Pagination


1. In this approach we will retrieve only page specific records from database
2. Memory will not be wasted
3. For every page load DB interaction will happen
4. For huge data sets this is recommended
Client Side Pagination
In this approach we will retrieve all records from the able and will manage pages in applications
 Memory consumption will be more
 DB Interaction only one time
 For small data sets this is recommended
Server side pagination implementation
1. What is page size ? -- How many records we need to display in page
2. Total records in Tbl? -- How many records are available in table
3. How many pages are required ? -
totalPages = (totalRecords / pageSize );
TestCase-1 : totalPages = 100/10 ---> 10
TestCase-2 : totalPages = 50/10 ---> 5
Test Case-3 : totalPages = 51/10 ---> 5 (We need extra page to display 51th record)
totalPages = (totalRecords / pageSize )+( (totalRecords%pageSize > 0)? 1: 0 );
TestCase-1 : totalPages = 100/10 + 0 ---> 10
TestCase-2 : totalPages = 50/10 + 0 ---> 5
Test Case-3 : totalPages = 51/10 + 1 ---> 6
Test Case-4 : totalPages = 59/10 + 1 ---> 6
Test Case-5 : totalPages = 52/10 + 1 ---> 6
Test Case-5 : totalPages = 60/10 + 0 ---> 6
-> For every table it is very important to maintain Primary Key column
-> Primary Key constraint is combination of below 2 constraints
a) NOT NULL
b) Unique
-> Primary key column value should be unique and it should not be NULL
-> If we ask end user to enter the data for primary key column value he may enter duplicate value
-> If end user tries to submit form data with duplicate column value then application can't save that
data to table due to Primary key constraint.
-> If we try to insert duplicate data to Primary Column Database will throws
UniqueConstraintViolation.
-> End users may not know about primary key constraints
-> To avoid this problem instead of asking end user to enter PK value application should generate
that value

Generators:
Generators are used to generate value for primary key column when record is inserting to table.

@Entity
@Table(name = "CUSTOMER_DTLS")
@Data
public class CustomerDtlsEntity {

@Id
@GeneratedValue
private Integer customerId;
private String customerName;
private String customerEmail; }
Generators
Using generators we can generate value for primary key column while inserting data
@GeneratedValue:
When we use this annotation internally it is using SequenceGenerator to generate value for
primary key column
Note: hibernate_sequence is the default sequence which will start with 1 and increments by 1.
Entity class with @GeneratedValue
@Entity
@Table(name = "CUSTOMER_DTLS")
@Data
public class CustomerDtlsEntity {

@Id
@GeneratedValue
private Integer customerId;
private String customerName;
private String customerEmail;

@GeneratedValue(strategy = GenerationType.IDENTITY)
-> It is database dependent
-> Doesn't support for Oracle
-> Supports for MySql
@GeneratedValue(strategy = GenerationType.SEQUENCE)
o Sequence is database dependent
o Oracle DB supports for Sequences but MySql DB doesn't for sequences
o When we specify GenerationType as SEQUENCE, Spring Data JPA using default
sequence
o (HIBERNATE_SEQUENCE)
o In Realtime it is not recommended to use default sequence (HIBERNATE_SEQUENCE)
o It is recommended to create a dedicated sequence for every primary key column

CUSTOMER_ID ---------------- CUSTOMER_ID_SEQ


USER_ID ---------------- USER_ID_SEQ
PRODUCT_ID ---------------- PROD_ID_SEQ

SEQUENCE CREATION IN DATABASE


CREATE SEQUENCE <SEQUENCE-NAME>
START WITH 1
INCREMENT BY 1;

Getting value from sequence


To get current value : select sequence-name.currval from dual;
To get next value : select sequence-name.nextval from dual;
Note: Every sequence should use unique name
create sequence CUSTOMER_ID_SEQ
START WITH 1
INCREMENT BY 1;

Configuring Custom Sequence Generator in Entity Class


@Id
@SequenceGenerator(
name="abc",
sequenceName="CUSTOMER_ID_SEQ",
allocationSize=1
)
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="abc")
private Integer customerId;

With this we mapped our primary column variable with CUSTOMER_ID_SEQ

When application inserting record into CUSTOMER_DTLS table it will read next value from
CUSTOMER_ID_SEQ for primary key column data.
Sequence generator & How to use Custom Sequence using Generator
@SequenceGenerator(name="" sequenceName="")
@GeneratedValue(strategy="", generator="")

Custom Generators
o We are having 11 predefined generators in Hibernate

o Every Generator having its own algorithm to generate value for Primary Key

 -> Few Generators will generate Numeric value and few generates will generate alpha
numeric value for Primary key column.

Custom Requirement
------------------
For my ORDER_DTLS table i want to generate primary key like below

OD1
OD2
OD3
OD4 etc....

For EMP_MASTER table i want to generate primay key like below


IBM1
IBM2
IBM3
IBM4 etc...

-> To satisfy above requirements we don't have any predefined generator

-> In this situation we need to go for Custom Generator

-> To develop Custom Generator or User Defined Generator we need to implement one interface
i.e IdentiferGenerator
Steps to develop an application using Custom Generator
-------------------------------------------------------
1) Create Standalone Spring Boot application with below dependencies
a)spring-boot-starter
b)spring-boot-starter-data-jpa
c)Oracle Driver
d)Project Lombok

2) Configure DataSource properties In application.yml

3) Create Entity class (Mapping with table)

4) Create CustomGenerator class by implementing IdentifierGenerator interface


(As per requirement we need to implement generate(..) method with our logic)

Note: Primary Key value generation logic will be available in generate( ) method

5) Specify CustomGenerator details in Entity class for Primary Key

6) Create Repository interface by extending Spring Data Repository

7) Test application functionality

----------------------------------------------------------------
create sequence order_id_seq
start with 1
increment by 1;

-------------------------------------------------------
@Entity
@Table(name = "ORDER_DTLS")
@Data
public class OrderDetailsEntity {

@Id
@Column(name = "ORDER_ID")
@GenericGenerator(
name="order_id_gen",
strategy="com.ashokit.generators.OrderIdGenerator"
)
@GeneratedValue(generator="order_id_gen")
private String orderId; // OD1 OD2

@Column(name = "ORDER_BY")
private String orderBy;

@Column(name = "ORDER_PLACED_DT")
private Date orderPlacedDate;

}
--------------------------------------------------------------------
public class OrderIdGenerator implements IdentifierGenerator {

@Override
public Serializable generate(SharedSessionContractImplementor session, Object object)
throws HibernateException {
Integer seqVal = null;
String prefix = "OD";
Connection con = null;
try {
con = session.connection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ORDER_ID_SEQ.NEXTVAL FROM
DUAL");
if (rs.next()) {
seqVal = rs.getInt(1);
}

} catch (Exception e) {
e.printStackTrace();
}
return prefix + seqVal;
}

}
-----------------------------------------------------------------------------------------------
05-Jun-2020
-----------

Schema Generation
-----------------

-> ORM frameworks are having support to generate schema in runtime

-> ORM frameworks can create table and can create sequence in runtime required for app

-> By Default Schema Generation mode will be OFF

-> To enable schema generation we will use ddl-auto property

spring.jpa.hibernate.ddl-auto=create/create-drop/update

-> We have several possible values for ddl-auto property

-> create
-> create-drop
-> update
-> validate
-> none
-> create means every time new table will be created

-> create-drop: it creates table and drops table at end of operaton

-> update: If table is not available it will create if table is already available it will just perform
operation

-> validate: It is used to validate schema details

Note: Don't enable this property in Production Environment

06-Jun-2020
-----------
Yesterday session : Auto DDL (create, create-drop, update and validate)

Today's Session : Profiles in Spring Boot

When we develop an application in realtime that application will be tested in multiple


environments before deploying to production.

Production : Live Environment

We will test our application in several environments


a) DEV

b) SIT

c) UAT

d) PILOT

For every environment several environment specific properties will be avilable


-------------------------------------------------------------------------------
a) DB properites

b) SMTP properties

c) Logging properties

d) Redis Server properties

e) Apache Kafka properties

f) Webservices/REST API Endpoint URL etc...

all the above details we are writing in application.properties file or application.yml file
08-Jun-2020
------------

Batch Code : 03-SBMS


Timings : 7:30 AM - 9 AM (Daily)

Spring Boot Basics Completed


Spring Data Completed

Pending Concepts (30-40 days)


------------------------------
Spring MVC (1 week)
Spring with REST (10 days)
Microservices(15 days)
Spring Cloud (4 days)
Spring MVC
----------
What is MVC?
Why we need to follow mvc?
What is Spring MVC?
Spring MVC Advantages
Spring MVC Architecture
Front Controller (Dispatcher Servlet)
Handler Mappers
Controllers
View Resolvers
Application Development using Spring MVC using Boot approach
Internals of applications
Spring Form Tag Libray
Form Based Applications Development
Form based applications with Spring Data
In Memory Database (H2)
Mongo DB integration
Making Jetty as Default Embedded Container
Deploying SpringBoot application to External Server
Spring Boot Actuators
Application development using Thymeleaf

What is MVC?
------------
M - Model

V - View

C - Controller
-> MVC is an universal design pattern

-> Using MVC design pattern we can develop loosely coupled applications

-> We can developer application in layered archicture in fashion

-> In this MVC design pattern

M - model (It deals with Data layer)

V - view (It deals with Presentaion layer) - UI

C - controller (It deals with Web layer)

-> If we develope our application using MVC then maintenence cost will be less in future
09-Jun-2020
------------

Yesterday's session : MVC

Today's session : Spring MVC


-> What is Spring MVC ?
--------------------------
Spring MVC is a module available in Spring framework

-> Using Spring MVC we can develope MVC based web application & we can develop distributed
applications

What is a Web application


-------------------------
-> The application which we are accessing from browser

-> Web applications are meant for C 2 B (Customer to Business)

-> End users will interact with web applications directley

Ex : Gmail, Flikart, Amazon, IRCTC etc....

What is a Distributed application


---------------------------------
-> The application which is interacting with another application is called as Distributed application

-> To develop distributed applications we will use Webservices

-> Using Spring MVC we can develop and access REST APIs

-> REST API & REST Client both we can develop using Spring MVC

-> Distributed applications are meant for B 2 B


(Business to Business)

Ex : Passport ----> Aadhar app


Zomoto -----> Banking apps
MakeMyTrip ---> Airlines apps

-> In Spring MVC, Components roles seperated very clearly seperated

-> Spring MVC supports for multiple presentation technlogies

-> Spring MVC supports for Forms development (They provided their own form tag library to simply
forms development)

-> Spring MVC supports form Form binding object

-> When we spring mvc for forms development it provides will things for us

a)It captures form data


b)It converts form data to corresponding data type
c)It binds form data to java object and provided object directley

-> Spring MVC supports for I18N applications development

-> Spring MVC supports for Inteceptors to intercept every request


10-Jun-2020
-----------
What is MVC?
What is Sping MVC?
What are the Advantages of Spring MVC?

Todays' Session:-
-----------------
Spring MVC Components
Spring MVC Architecture
Request execution flow in Spring MVC application

Spring MVC Components


---------------------
1) Front Controller (DispatcherServlet)
2) Handler Mapper
3) Controller
4) ModelAndView
5) ViewResolver
6) View

-> Spring MVC module is part of Spring framework

-> In Spring 1.x version we have Spring MVC and Spring Web MVC modules

-> Spring 2.x version web module and mvc module are combined and released Spring Web MVC
module
-> Spring MVC module is used to develop below types of applications

a) Web applications
b) Distributed applications

-> This Spring Web MVC module is developed based on 2 design patterns

a) MVC Design Pattern


b) Front Controller Design Pattern

FrontController
---------------
-> FrontController is responsible to perform pre- processing and post processing of incoming
request

-> For example capturing form data we can consider as pre-processing request

-> For example sending response back to client in client understandable form can be called as Post
Processing of request

-> In Spring Web MVC based application we will use DispatcherServlet as a front controller

-> DispatcherServlet is a pre-defined servlet provided by Spring MVC module

-> Dispatcher will be called as Spring framework Servlet

Handler Mapper
--------------
-> Handler Mapper is a pre-defined class available in Spring MVC

-> Handler Mapper is responsible to identify request handler(Controller)


-> The program which is handling incoming request is called as Request Handler

-> Controllers will be called as request handlers

-> Handler Mapper will identify request handler and returns handler details to DispatcherServlet

Controller
----------
-> Controller is a program which is responsible to handle request

-> Using Spring MVC module we can create our own Controllers

-> In Spring MVC some predefined controller classes are available like below

a)SimpleFormController
b)AbstractCommandController
c)MultiActionController etc...

-> We can create User define controller using @Controller annotation

ModelAndView
------------
-> Once Request processing is completed Controller will return ModelAndView object to
DispatcherServlet

-> ModelAndView is a pre-defined class available in Spring MVC module

-> In ModelAndView class, model represents data and view represents logical view name

Model -----> Holds Data

View ------> Logical view file name


View Resolver
-------------
-> In Spring MVC we have multiple view resolver classes+

a)InternalResourceViewResolver
b)URLBasedViewResolver
c)XmlViewResolver etc....

-> These view resolvers are responsible to identify view files (location & extension)

View Component
----------------
-> It is responsible to render model data on view file

Request Execution Flow In Spring MVC Application


------------------------------------------------
1) Incoming Http Request will be recieved by DispatcherServlet. DS is a predefined Servlet class in
Spring MVC and it is acting as Front Controller.

2) DispatcherServlet will send requested URL to HandlerMapper

3) HandlerMapper will identify request handler which is responsible to handle this request and will
send request handler details to DispatcherServlet.

4) DispatcherServlet will call respective Controller class method

5) Controller method will process request and will send ModelAndView object to DispatcherServlet

Model ---> Data


View ---> Logical File Name
6) DispatcherServlet will send view name to ViewResolver

7) ViewResolver will identify view location & extension and sends data to DispatcherServlet

8) DispatcherServlet will give model and view details to View Component

9) Model data will be rendered on view sends back to DispatcherServlet

10) DispatcherServlet will send response back for the recieved request

FB Group Name : TEK Leads

YouTube Channel : Ashok IT


11-Jun-2020
-----------
Yesterday's session : Spring MVC Architecture

Today's session : Building First Web Application using Spring Boot

Steps to develop Web App using Spring Boot


------------------------------------------
1) Open Spring Tool Suite (STS) IDE and Create Spring Starter Project

(File ---> New ---> Project --> Spring Starter Project)

2) Select Dependencies required for application at the time of application creation

a)spring-boot-starter-web (web-starter)

Note : spring-boot-starter-web will provide below 3 things


----------------------------------------------------------
1) We can build web apps using Spring MVC
2) Web can build Restful apps
3) Apache Tomcat will be provided as default container

3) Create Controller class and methods required for application

a) @Controller (to represent java class as Spring Controller)


b) @RequestMapping (to map method to url-pattern)

4) Create View Component (here i am using jsp)

5) Add below configurations in application.properties file


1) Change server port number (if required)
2) Configure ViewResolver with prefix and suffix

6) Run Spring Boot application and test it.

Key Points
-----------------
-> For Running Spring Boot based applications we no need to install any server

-> Spring Boot Supporting for Embedded Continaers (Apache Tomcat is default Embedded Container)

-> Embedded Apache Tomact Container run on port no : 8080

-> If we want to change the port no then we should add below property in application.properties file

server.port = 8081

-> To parse JSP files in Boot application, we need tomcat embed jasper dependency. Add below
dependency in pom.xml file

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency
Yesterday's session : Web app development using Spring Boot

Today's session : Developing second web app using Boot


-----------------------------------------------------------
12-Jun-2020
--------------------------------------------------------

Procedure to develop web app using SpringBoot


---------------------------------------------
1) Create Spring starter project in STS IDE

(File -> New --> Project--> Spring Boot --> Starter Project)

2) Choose below dependencies while creating boot application

a)spring-boot-starter-web
b)tomcat-embed-jasper

-> spring-boot-stater-web providing below 3 functionalities


a)Support to build web app based on Spring MVC
b)Support to build RESTful service
c)Provides Tomcat as Embedded Container

-> It is used to compile jsp files(we don't add it view will be downloaded instead of rendering)

3) Create User-defined Spring Controller class, write required methods in controller class and bind
those controller methods to url patterns

a)@Controller (to represent java class as Spring Controller)


b)@RequestMapping (to bind method to url-pattern)

Note : Controller methods are going to return ModelAndView object

Model ---> It is used to store data in the formof Key & value pair
View ---> Logical View Name (only file name without extension)

4) Create View Component and access data available in Model object using key

5) Configure below details in application.properties or application.yml file

a)Embedded Container Port


b)View Resolver

6) Run Spring Boot application from main method (Start class)

7) Test our application functionality


Yesterday's sesion : Web App Creation using Spring Boot

Today's session : Working with Multiple Controllers

------------------------------------------------------------
13-Jun-2020
------------------------------------------------------------

-> When we create SB application by default start class will be provided

-> In Spring Boot, web app execution also will start from main method

-> For developing web apps using Spring Boot, we need web starter

-> web starter provides support for mvc, rest api and embedded container
-> Spring Boot will provide Apache tomcat as embedded container

-> In spring boot, default port no for embedded container is 8080

-> To change server port in SPringBoot we can use below property

server.port = 9090

-> By Default Spring Boot will not consider Project Name in URL ( Context-Path)

-> Every method in controller should have unique url-pattern

---------------------------HomeController----------------------------------
@Controller
public class HomeController {

@RequestMapping("/home")
public String displayHomePage(Model model) {
model.addAttribute("msg", "This is home page0");
return "homePage";
}
}

URL to access : http://localhost:8082/07-SB-MultiController-Web-App/home

-------------------------DateController------------------------------
@Controller
public class DateController {

@RequestMapping("/date")
public ModelAndView displayDate() {
ModelAndView mav = new ModelAndView();
String msgTxt = "Hello, Today's date : " + new Date();
mav.addObject("msg", msgTxt);
mav.setViewName("displayDate");
return mav;
}
}

URL to accesss: http://localhost:8082/07-SB-MultiController-Web-App/date

-------------------------------------------------------------------------

Note : By default embedded cotainer wil not consider projectname in URL

-> If you add project name then we can't access resources

How to add Context-Path in Spring Boot application?


----------------------------------------------------

server.servlet.context-path=/App

Note: If we add this context-path, then it is mandatory to specify in URL to access resources.

Note: Context path willstart with / and it should not end with /
Yesterday's session : Working with Multiple Controllers

Today's session : Working with Controller methods


---------------------------------------------------------

-> To create Controller we are using @Controller annotation

-> @Controller annotation is a stereotype annotation


-> Inside controller we will write methods to handle requests

-> Controller methods we will bind to URL patterns

-> @RequestMapping annotation we will use to bind Controller method to URL pattern

--------------------Approach-1------------------------------------
@Controller
public class HomeController{

@RequestMapping("/home")
public ModelAndView displayHomePage(){
//logic
return mav;
}
}
----------------------------------------------------------------------
-> By default @RequestMapping annotation will bind our method to HTTP GET Request Method

-> To bind our controller method to HTTP Post request method we should write like below

@RequestMapping(value="/home",method=RequestMethod.POST)

-> One controller method can bind to multiple url patterns

@RequestMapping(value={"/","/index","/home"})

-> From Spring 4.0 version on wards we can use below methods to bind Controller methods to URL
pattern

1) @GetMapping :-> To bind our method to Http Get request


Ex :

@GetMapping("/home")
public ModelAndView displayHomePage(){
//logic
return mav;
}

2)@PostMapping :-> To bind our method to Http post request

@PostMapping("/dashboard")
public ModelAndView displayDashboardPage(){
//logic
return mav;
}

3)@PutMapping :-> To bind our method to Http PUT request

@PutMapping("/dashboard")
public ModelAndView displayDashboardPage(){
//logic
return mav;
}

4)@DeleteMapping:-> To bind our method to HTTP DELETE request

@DeleteMapping("/dashboard")
public ModelAndView displayDashboardPage(){
//logic
return mav;
}
--------------------Approach-2------------------------------------
@Controller
public class HomeController{

@GetMapping("/index")
public String displayHomePage(Model model){
//logic
return "indexPage";
}
}
----------------------------------------------------------------------
Note: When Spring Controller method returns String value then DispatcherServlet will consider that
as a Logical View Name.

Note: Taking Model object as a parameter is optional. If we want to send any data from controller to
UI then only Model object is required.

-> From controller method we can return raw response also

@GetMapping("/validate")
public @ResponseBody String validEmail(){
//logic
return msg;
}
}
16-Jun-2020
-----------

-> When we add @RequestMapping annoation at controller method it will bind by default to
HTTP GET Request. Writing method=RequestMethod.GET is optional

@RequestMapping("/index")
public String index(){
//logic
}
or

@RequestMapping(value="/index",method=RequestMethod.GET)
public String index(){
//logic
}

-> Note: The above two methods are same

-> One controller method can bind to multiple url patterns like below
-------------------------------------------------------------------------------
@Controller
public class DemoController {

@RequestMapping(value = { "/", "/index", "/home" })


public ModelAndView index() {
ModelAndView mav = new ModelAndView();

// set data to model in key-value format


mav.addObject("msg", "Welcome to Spring MVC with Spring Boot..!!");
// set logical view name
mav.setViewName("index");

return mav;
}
}
----------------------------------------------------------------------------------
-> We can send request to above controller method in below ways

1) http://localhost:<port-no>/
2) http://localhost:<port-no>/index
3) http://localhost:<port-no>/home

Why we need to bind one method to more than one url-pattern?


------------------------------------------------------------
-> When user enters ---> www.facebook.com in browser login page should be displayed

-> when user click on logout --> login page should be displayed

-> Here for different requests we need to process with same logic

-> For this we can write our controller method like below

@RequestMapping(value={"/", "/index", "/logout"})


public String index(){
//logic
return "index";
}
----------------------------------------------------------------------------------

-> Every Controller method we should bind to unique url-pattern


-> In below scenario, both methods are binded to HTTP GET request and both are having "/home" as
URL-pattern. In this situation DispatcherServlet will get confused which method it has to execute
when request comes for "/home"

@RequetMapping(value={"/", "/index", "/home"})


public String index( )

@RequestMapping("/home")
public String home()

-> Note: We can bind multiple methods to same url pattern if they are binded to Different HTTP
Request methods

@RequetMapping(value={"/home"})
public String index( )

@RequestMapping(vallue="/home",method=RequestMethod.POST)
public String home()

-> When multiple developers are working on web layer, there is a possibility to use same url patterns
and same http request methods for more than one controller method which results ambiguity
problem.

-> To avoid this problem it is recommended to specify URL pattern at class level also along with the
method level.

@Controller("/demo")
public class DemoController {
//methods goes here
}

@Controller("/user")
public class UserController {
//methods goes here
}

Yesterday's session : Request Mappings

Today's session : Sending Data From Controller To UI


--------------------------------------------------------
17-Jun-2020
--------------------------------------------------------

-> Every Controller method should be binded to URL pattern

-> To bind methods to URL pattern we will use @RequestMaping or Spring4.0 introduced
annotations like @GetMapping and @PostMapping

-> One method can be binded to more than one URL pattern

-> To avoid ambiguity problems we will differentiate Request mappings at both class level and
method level

@Controller
@RequestMapping("/user")
public class UserController{

@RequestMapping(value="/signup")
public String displaySingUpPage(){
//logic goes here
}
}

URL to access above method : http://localhost:port/user/signup


What is the difference between below code snippets?
---------------------------------------------------
@Controller("/user")
public class UserController{

@Controller
@RequestMapping("/user")
public class UserController{

-> First part will represent only bean name

-> Second part will represent controller with URL-pattern

-> We can bind Controller class to more than one url pattern

-------------------------------------------------------------------------------
@Controller
@RequestMapping(value = { "/user", "/user1" })
public class UserController {

@GetMapping(value = { "/index", "/index1" })


public String index(Model model) {
// set data in model to send to ui
model.addAttribute("msg", "Hey User, Good Morning..!!");
return "index";
}
}
----------------------------------------------------------------------------------------
The above controller method can be accessed in below ways

1) http://localhost:port/user/index
2) http://localhost:port/user/index1
3) http://localhost:port/user1/index
4) http://localhost:port/user1/index1

-> In controller methods we can return ModelAndView object or we can return direct 'String' object

-> In ModelAndView object class we have methods to set data to model obj & to set view name

ModelAndView mav = new ModelAndView( );


mav.addObject(String key, Object value);
mav.setViewName(String viewName);

-> If we take String as a return type for Controller method, by default DispatcherServlet will consider
that as Logical view Name.

-> When we are taking String as return type for Controller method then how to send the data from
Controller method to UI?
-----------------------------------------------------------------------------------------
To send data from Controller to UI we will use Model

cc
How to access model data in View File?
--------------------------------------
Using Expression Language we can access data available in model scope

Ex: ${key}
---------------------------------------------------
public String index( ){
return "indexPage"
}
In this approach we can't send data from Controller to UI
---------------------------------------------------------

Can we return direct response from Controller method?


-----------------------------------------------------
Yes, using @ResponseBody

-> When we use @ResponseBody annotation for controller method, then DispatcerServet will not
execute ViewResolver.

@Controller + ResponseBody ===> Restcontroller

Yesterday's Topic : Controller methods

Today's Topic : Form based applications


----------------------------------------------
18-Jun-2020
----------------------------------------------
-> In web application we will have several forms

Ex : Login, Registration, Forgot Password, Search Form

-> These forms are used to collect data from end user

-> In our web applications we can develop forms using below technolgies

a) HTML
b) JSP
c) JS frameworks

Requirement:
-------------
Develop a form with below 4 text fields

1) Username
2) Password
3) Email
4) Phone Number

Steps to develop First Form Based Application using Spring Boot


----------------------------------------------------------------
1) Create Spring Boot starter project with below dependencines

a)spring-boot-starter-web
b)tomact-embed-jasper

2) Create Controller with below methods

a) loadForm
b) handleSubmitBtn
3) Create View Components
a) register.jsp (to display form)
b) registerSuccess.jsp (to display success msg)

4) Configure below properties in application.yml file


a) server port
b) view resolver
c) context path

http://localhost:8081/UserApp
or
http://localhost:8081/UserApp/register

-> To capture form data we are using HttpServletRequest object as Controller method parameter

-> Form is binded to POST method, so form data will be sent to server in Request body.

-> To capture form data we are using HttpServletRequest method req.getParameter(String key).

-> To send data from controller to UI we are using Model object

Yesterday's session : Form based application

Today's session : Form Binding Object


----------------------------------------------
19-Jun-2020
-------------------------------------------------

-> We used HTML tags to develop registration form

-> In controller we have 2 methods


a)method for loading form (GET)
b)method for handling form submission (POST)

-> Once form is submitted, request going to controller method which is binded to given action url in
form tag.

<form action="register" >


<fields>
</form>

-> action attribute represents "request-handler url-pattern"

-> method attributre represents what type of HTTP request should be sent to server.

-> POST request means form data will go to server in request body

-> If we don't specify method as post, then by default it will be considered as GET request method.

-> If we submit form with GET request then form data will be sent to server as query parameters (we
can see the data in url)-security problems will be there.

GET Method Use cases


--------------------
-> If we want to send data from Controller to UI then we will bind our controller method to GET
Request method.
-> If controller method is expecting sensitive information from client then we will bind our controller
method to POST request methods.

-> In post request data wil be sent in request body (which is safe).

-> If we use GET request for form submission below are the challenges

a)Form data will be sent to serer in URL


b)GET req can carry onl 1024 charaterc in URl
c)Binary data can't sent to server using GET req

@PostMapping("/register")
public String handleSubitBtn(HttpServletReq req, Model model){
//capturing form data

//setting data to model

//returning logical view name


}
HttpServletRequest ---> To capture data coming in Request

String name = req.getParameter("uname");

-> If we have more fields in form then we should write boiler plate code to capture form data.

-> In application we will have several forms and every form will have several fields then we should
write lot of boiler plate code in our application.

-> To avoid this boiler plate code, Spring MVC provided Form Bindg OBject mechanism.

----------------------------------------------------
@PostMapping("/register")
public String handleSubmitBtn(User user, Model model) {
// Sending Data from Controller to UI
String succMsg = "Registration completed successfully..!!";
model.addAttribute("msg", succMsg);

// Returning Logical View Name


return "regSuccess";
}
---------------------------------------------------------------

Yesterday's session : Form Binding Object


Today's session: Spring Form Tag library
----------------------------------------------
20-Jun-2020
----------------------------------------------
-> Form Binding objects are used to store form data

-> When we submit form, DispatcherServlet will capture form data and will store into form binding
object

-> DispatcherServlet providing flexibility in form binding

-> When we submit form all data will transfer to server in the form of String. DispatcherServlet will
convert that data according form binding object filed data types.

-> With this form binding mechanism we can avoid lot of boiler plate code (We no need to write
logic to capture form data using request.getParameter("key"))
--------------------------------------------------------------------

Spring MVC Form Tag Library


------------------------------

-> Spring MVC module provided form tag library to simply forms development in our web application

-> As part of this tag library we have several pre-defined tags like

a)input
b)password
c)select
d)option & options
e)radioButton & radioButtons
f)checkbox & checkboxes etc...

-> To work with Spring MVC form tag library, we need to create Form Binding class
-> The java class which is representing structure of form data is called as Form Binding class

-> If we have form binding class then form data can be stored to form binding class object and vice
versa

How to bind form fields to Form Binding Class Variables


-------------------------------------------------------

<form:form action="" modelAttribute="" method="">


Username : <form:input path="uname"/>
Password : <form:password path="pwd"/>
</form:form>

-> action attributre represents request handler url (handler method)

-> method attribute represents HTTP request type (default is GET)

Note: For forms we should use POST request

-> modelAttribute represents mapping between form and form binding object

-> path attribute represents mapping between form field and binding class variable
Last session : Loading Student Registration Form

Today's session : Student Registration Form Submission


--------------------------------------------------------------------
22-Jun-2020
-------------------------------------------------------------------

-> To simply forms development, Spring MVC module provided form tag library for us.

-> As part of form tag library we are having below tags

a)<form:form />
b)<form:input/>
c)<form:password/>
d)<form:radioButton>
e)<form:radioButtons/>
f)<form:select/>
g)<form:option/>
h)<form:options/>
i)<form:checkbox/>
j)<form:checkboxes/> etc...

-> In order to use Spring MVC Form Tag library we need to add Taglib directive in our view
component.

Syntax to configure taglib directive


-------------------------------------
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

-> Spring MVC Form tags will be converted HTML tags in background

-> To load Student Registration Form we have written one method in Controller which is binded to
HTTP GET Request

@Controller
public class StudentController{

@GetMapping(value={"/","/regStudent"})
public String loadForm(Model model){

//form binding class


Student s = new Student( );

//sending data to view


model.addAttribute("stu",s);

//logical view name


return "registerStudent";

}
}

<form:form action="" modelAttribute="" method="">


Username : <form:input path="uname"/>
</form:form>

Form Submission
---------------
-> To submit a form we should write action attribute in form tag.

-> action attribute represents request handler url (controller method url)

-> For Form we should specify method as POST then form data will go server in Request Body

<form:form method="POST">

</form:form>

-> If we don't specify method attribute like above then it will consider as GET Request.

-> If we submit a form with GET request, then form data will be appended to URL (it will be visiable).
When we are dealing with sensitive information security will not be avilable.

If we submit a form with GET request below are the drawbacks


------------------------------------------------------------
1) Form data will be displayed in URL
2) Browsers will support upto 1024 characters only in URL
3) MIME data can't be sent in URL (images, videos and files)

Controller Method to handle form submission


--------------------------------------------
@Controller
public class StudentController{
@PostMapping(value="/registerStudent")
public String handleRegisterBtn(Student s, Model model){

//form data operation (store to db)

//send response to UI
model.addAttribute("succmsg","Registration completed");

return "registerStudent";
}

}
Yesterday's session : Form submission

Today's Topic : @ModelAttribute annotation


-------------------------------------------
23-Jun-2020
-------------------------------------------
-> For Form submissions we should use POST Request

-> In post request data willbe sent in request body

-> In GET request data will go in URL (not secureD)

By Default Embedded Container will not reload the changes made in project

When ever we make a change we need to re-start the server

When we are working on development part, several times we will make code changes. For every
code change if we want to restart the server it will take more time (Time waste)
To avoid this problem we can use 'DevTools'

DevTools will reload the changes and will re-start Boot application

To Enable Dev Tools in Spring Boot application, we should add below dependency in pom.xml.
-----------------------------------------------------------
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
-----------------------------------------------------------

What is @ModelAttribute
----------------------
-> This is one of the important annotation in Spring MVC module

-> It binds a method parameter or method return value to a named attributed and it exposes that to
a view.

This annotation we can use at 2 places


---------------------------------------
1) At method level
------------------
@ModelAttribute
public void m1(Model model){
//set data to model scope
}

If a controller having a method with @ModelAttribute annotation then that methdod will be
executed for every request

Use case
--------
-> To load common values for all views

2) As method parameter
-----------------------
@PostMapping("/register")
public String handleSubmitBtn(@ModelAttribute("student") Student s,
Model model){

return "lvn";
}

-> To capture data coming in request into form binding object then we will at method parameter.

Steps to develop Book Store application


----------------------------------------
1) Create Spring Boot web application with below dependencies

a)spring-boot-web-starter
b)spring-boot-starter-data-jpa
c)Oracle driver
d)project lombok
e)tomcat-embed-jasper
f)devtools

2) Create Entity class and map it to DB table


3) Create Repository interface using Data JPA Repositoy

4) Create Form Binding Class

5) Create Servie Layer interface & implementation components

6) Create Controller with required methods for request handling

7) Create View Components

8) Configure below properties in application.yml file


a) Server Port
b) View Resolver Configuration
c) Data Source Configuration

9) Start Boot application and test functionality

Yesterday' topic: Displaying data using JSTL

Today's topic : Request Redirection & Dynamic values to dropdowns, radioButtons & Checkboxes
------------------------------------------------------------------
27-Jun-2020
------------------------------------------------------------------

-> In Controller we will write methods to handle request.

-> Controller methods will be binded to HTTP Request with URL-Pattern

http://localhost:9090/login

You might also like