Professional Documents
Culture Documents
Spting Boot
Spting Boot
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
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
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....
-> 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
Note: Primary Key value generation logic will be available in generate( ) method
----------------------------------------------------------------
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 can create table and can create sequence in runtime required for app
spring.jpa.hibernate.ddl-auto=create/create-drop/update
-> create
-> create-drop
-> update
-> validate
-> none
-> create means every time new table will be created
-> update: If table is not available it will create if table is already available it will just perform
operation
06-Jun-2020
-----------
Yesterday session : Auto DDL (create, create-drop, update and validate)
b) SIT
c) UAT
d) PILOT
b) SMTP properties
c) Logging properties
all the above details we are writing in application.properties file or application.yml file
08-Jun-2020
------------
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
-> If we develope our application using MVC then maintenence cost will be less in future
09-Jun-2020
------------
-> Using Spring MVC we can develope MVC based web application & we can develop distributed
applications
-> Using Spring MVC we can develop and access REST APIs
-> REST API & REST Client both we can develop using Spring MVC
-> Spring MVC supports for Forms development (They provided their own form tag library to simply
forms development)
-> When we spring mvc for forms development it provides will things for us
Todays' Session:-
-----------------
Spring MVC Components
Spring MVC Architecture
Request execution flow in Spring MVC application
-> 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
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
Handler Mapper
--------------
-> Handler Mapper is a pre-defined class available in Spring MVC
-> 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...
ModelAndView
------------
-> Once Request processing is completed Controller will return ModelAndView object to
DispatcherServlet
-> In ModelAndView class, model represents data and view represents logical view name
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
3) HandlerMapper will identify request handler which is responsible to handle this request and will
send request handler details to DispatcherServlet.
5) Controller method will process request and will send ModelAndView object to DispatcherServlet
7) ViewResolver will identify view location & extension and sends data to DispatcherServlet
10) DispatcherServlet will send response back for the recieved request
a)spring-boot-starter-web (web-starter)
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)
-> 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
(File -> New --> Project--> Spring Boot --> Starter Project)
a)spring-boot-starter-web
b)tomcat-embed-jasper
-> 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
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
------------------------------------------------------------
13-Jun-2020
------------------------------------------------------------
-> 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
server.port = 9090
-> By Default Spring Boot will not consider Project Name in URL ( Context-Path)
---------------------------HomeController----------------------------------
@Controller
public class HomeController {
@RequestMapping("/home")
public String displayHomePage(Model model) {
model.addAttribute("msg", "This is home page0");
return "homePage";
}
}
-------------------------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;
}
}
-------------------------------------------------------------------------
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
-> @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)
@RequestMapping(value={"/","/index","/home"})
-> From Spring 4.0 version on wards we can use below methods to bind Controller methods to URL
pattern
@GetMapping("/home")
public ModelAndView displayHomePage(){
//logic
return mav;
}
@PostMapping("/dashboard")
public ModelAndView displayDashboardPage(){
//logic
return mav;
}
@PutMapping("/dashboard")
public ModelAndView displayDashboardPage(){
//logic
return mav;
}
@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.
@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
}
-> One controller method can bind to multiple url patterns like below
-------------------------------------------------------------------------------
@Controller
public class DemoController {
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
-> 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("/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
}
-> 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
}
}
@Controller
@RequestMapping("/user")
public class UserController{
-> We can bind Controller class to more than one url pattern
-------------------------------------------------------------------------------
@Controller
@RequestMapping(value = { "/user", "/user1" })
public class UserController {
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
-> 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
---------------------------------------------------------
-> When we use @ResponseBody annotation for controller method, then DispatcerServet will not
execute ViewResolver.
-> 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
a)spring-boot-starter-web
b)tomact-embed-jasper
a) loadForm
b) handleSubmitBtn
3) Create View Components
a) register.jsp (to display form)
b) registerSuccess.jsp (to display success msg)
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).
-> Once form is submitted, request going to controller method which is binded to given action url in
form tag.
-> 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.
-> 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
@PostMapping("/register")
public String handleSubitBtn(HttpServletReq req, Model model){
//capturing form data
-> 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);
-> When we submit form, DispatcherServlet will capture form data and will store into form binding
object
-> 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 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
-> 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
-> To simply forms development, Spring MVC module provided form tag library for us.
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.
-> 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 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.
//send response to UI
model.addAttribute("succmsg","Registration completed");
return "registerStudent";
}
}
Yesterday's session : Form submission
By Default Embedded Container will not reload the changes made in project
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.
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.
a)spring-boot-web-starter
b)spring-boot-starter-data-jpa
c)Oracle driver
d)project lombok
e)tomcat-embed-jasper
f)devtools
Today's topic : Request Redirection & Dynamic values to dropdowns, radioButtons & Checkboxes
------------------------------------------------------------------
27-Jun-2020
------------------------------------------------------------------
http://localhost:9090/login