Advance Java
Advance Java
1. JDBC
2. Servlet and JSP
3. Java Frameworks - Hibernate, Spring
4. REST APIs using Spring Boot
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
JDBC:
-stands for Java to Database Connectivity.
-It is an API(Application Programming Interface) which allows Java applications to interact with DB.
-Like Java, every DB Vendor also provides its own API which is known as Vendor Specific API.
-It simplifies access for all the clients who want to interact with DB.
-Since both APIs are written as per their standards, there are conflicts. These conflicts can be resolved
using a mediator known as JDBC Driver.
-Driver is a program which converts JDBC calls into some format which is understood by Vendor Specific
API.
-Typically, JDBC Drivers are of 4 types:
-Type 1 :
-It is called as JDBC - ODBC bridge.
-It uses a third party library, ODBC(Open Database Connectivity) which is provided by Microsoft.
-It converts JDBC calls into some format which is understood by ODBC.
-It is not much recommended in large scale applications or even production environment because of
following limitations :
a) It is the slowest.
b) It is Platform Dependent - (specific to windows).
c) Every client machine needs ODBC configuration setup.
-Type 2 :
-It is called as Native API, Partly Java Driver.
-It is a combination of Java and DB Vendor Specific implementation.
-It does not use any third party library.
-Benefits over Type 1:
a) It is faster.
b) It is platform independent.
-Limitation :
-Since it uses DB Specific Native API for communication, every client machine must have this API
installed.
-Type 3 :
-It is called as intermediate DB Access Server.
-It is completely different from other drivers.
-It is used especially when a client program wants to interact with multiple database servers.
-It uses a middleware known as Intermediate DB Access Server which acts as a router.
-Type 4 :
-It is called as Vendor Specific, Pure Java Driver.
-Every DB Vendor provides its own driver for its Database.
-It uses TCP Socket connection for communication.
-Benefits :
a) It is the fastest.
b) It is platform independent.
c) It does not require any configuration setup on client machine.
-It is highly recommended for production environment and even for large scale applications.
-------------------------------------------------------------------------------------------------------------------------
Getting started :
In order to write any JDBC program there are certain steps to be followed :
i. Load the driver.
ii. Establish connection with DB.
iii. Obtain some statement.
iv. Execute SQL Query.
v. In case of SELECT query, obtain ResultSet(Record set) and perform navigation.
3) Auto-Closing of resources :
Since all JDBC resources are extension to java.lang AutoCloseable, they can be opened using
try-with-resources construct so that they can be closed of their own.
2. PreparedStatement :
-It is a sub-interface of ’Statement’.
-It is used to execute parameterized queries.
-It creates the query only once and caches the same.
-This allows execute same query repeatedly with different set of parameter values without hampering
the performance.
3. CallableStatement :
-It is a sub-interface of ’PreparedStatement’.
-It is used to invoke stored procedures available on DB side.
-------------------------------------------------------------------------------------------------------------------------
Transaction Management :
-In any business application, Transaction Management is an important activity.
What is Transaction?
Transaction is a set of operations that must execute in a single unit.
-Transactions must be atomic (Execute All or None) otherwise the data is left in inconsistent state.
-Whenever, any DML operations is performed from Java towards DB, by default it gets commited.
Therefore, it is not possible to rollback the transaction even if it is required.
-This causes the problem of data inconsistency.
-Therefore, it is necessary to disable ’auto-commit’.
-’Connection’ interface provides relevant methods for Transaction Management.
1) setAutoCommit(boolean)
2) commit()
3) rollback()
-However, to develop different types of applications, Java provides its variants (platforms) :
1. Java SE (Java Standard Edition)
2. Java EE (Java Enterprise Edition) => Jakarta Enterprise Edition
3. Java ME (Java Micro Edition) (Outdated because of Android)
-Java SE platform can be used for developing Desktop or Simple N/W based applications.
-For developing web applications, Java EE (Jakarta EE) platform has to be used.
What is Component?
A component is an application level reusable piece of code.
Types of components :
1. Unmanaged :
-When the components are required to be instantiated explicitly using ’new’ keyword, then they are
called as Unmanaged Components.
-Generally, Java SE platform involves Unmanaged components.
2. Managed :
-When the components are not required to be instatntiated explicitly; rather they get instantiated
implicitly, then they are called as Managed Components.
-Generally, Jakarta EE platform involves Managed components.
Types of Managed Components :
1. Web Component :
When a component is responsible for accepting a Web Request and generating a Web Response,
then that component is called as Web Component.
Types of web component :
1. Servlet
2. JSP
2. Business Component :
When a component is responsible for handling a business logic (domain specific logic), then that
component is called as Business Component.
It is taken care by EJB => Enterprise Java Beans.
How components are managed?
Components are managed using a runtime environment known as Container.
-------------------------------------------------------------------------------------------------------------------------
There are two types of containers :
1. Web Container :
It is a runtime environment responsible for managing web components like Servlet and JSP.
2. EJB Container :
It is a runtime environment responsible for managing business components like EJB.
2. Application Server :
-It is an extension to Web Server.
-It provied Web Container as well as EJB container.
-There are several application servers available in market.
e.g., WebLogic by Oracle Corporation
WebSphere by IBM
JBoss by RedHat
GlassFish by Oracle Corporation
WildFly by RedHat
-------------------------------------------------------------------------------------------------------------------------
Servlet :
What is Servlet?
Servlet is a web component used to extend the functionality of web server.
-It runs on server side and therefore can be used to handle server side processing.
-It can be used to generate dynamic web contents.
Implementing Servlets :
-Servlets are implemented using a Java class which is called as Servlet Implementation Class.
-This class must make use of some API known as Servlet API.
-The Servlet API mainly consists of two packages :
1. jakarta.servlet
2. jakarta.servlet.http
-The ’jakarta.servlet’ package mainly provides following :
1. Servlet (Interface)
2. GenericServlet (Class)
3. ServletRequest (Interface)
4. ServletResponse (Interface)
-When the servlet is requested, every time service() method gets invoked.
-The service() method available in HttpServlet class identifies the type of incoming HTTP request.
-HTTP request is of several types :
1. GET
2. POST
3. PUT
4. DELETE
5. HEAD
6. OPTIONS
7. TRACE
-Once the type is identified, it invokes respective ’doXXX()’ method from ’HttpServlet’ class.
e.g., GET => doGet()
POST => doPost()
-In order to customize the implementation these methods need to be overridden in the sub class.
-When the server is requested by typing its URL in browser’s address bar, always HTTP GET request is
made.
-------------------------------------------------------------------------------------------------------------------------
Requesting a servlet :
A servlet can be requested using several options :
1. Using Browser’s address bar.
2. Using HTML anchor tag : ’<a>’
3. Using HTML Form : ’<form>’
4. Using an Applet (outdated)
5. Using another Servlet
6. Using JSP
-------------------------------------------------------------------------------------------------------------------------
HTML Form Processing :
-In web applications, accepting data from end user using HTML form is a very common requirement.
-Whatever data is entered by user is needs to be processed on server side and generate the response
accordingly.
-This technique is known as HTML form processing.
(
Servlets can be configured by two ways :
1. web.xml
(Mandatory till version 2.5 version 3.0 onwards optional)
2. @WebServlet annotation
)
-When client makes a request by providing some input, that data is sent towards server via HTTP
request.
-That data is known as request parameter. It is in the form of name-value pair.
-In order to capture this data, ’HttpServletRequest’ object is used.
-It provides a method : String getParameter(String)
<value> <name>
-HTML Form and GET Request :
-When data is sent towards servlet via HTML form, by default always HTTP GET request is made.
-In case of GET request, parameters are appended to the URL using ’?’ notation. They are seperated
using ’&’ notation.
-Since they are directly exposed, it leads to secure concerns.
-Therefore, in order to avoid such things, HTTP POST request is used.
-To make POST request, use "method = ’post’" setting for HTML <form> element.
2. jakarta.servlet.ServletContext :
-It is used to maintain application level information.
-Its object is created for the whole application.
3. jakarta.servlet.http.HttpSession :
-It is used to maintain session level (user level) information.
-It is used for session management.
-Its object is created for every user.
-------------------------------------------------------------------------------------------------------------------------
Session Management :
-HTTP is a stateless protocol. It does not maintain any conversational state along with the client.
-In a web application, to perform some transaction e.g. Ticket booking, Food order booking,... client has
to make multiple request towards server. Server has to maintain state for every client.
-Maintaining the state for every client is known as session management or session tracking.
-For every client a session must be available. It is used to maintain a client specific information.
-There are four options available for session mananagement :
1. URL Encoding
2. Hidden Form Fields
3. Cookies
4. Servlet API
-Using HtttpSession :
-The object of type ’HttpSession’ is used to maintain client specific information(state).
-It is obtained using ’getSession()’ method from : HttpServletRequest
-This method checks whether the session for the corresponding user is available or not.
-If not available, creates a new one and returns that.
-If avaialble, returns the existing one.
-The HttpSession inteface provides ’isNew()’ method to check whether the session is already created or
not.
Why JSP?
-In a web application, there are mainly two roles : Web Developer & Web Designer
-Web Developer needs to be expert in logic whereas Web Designer needs to expert in presentation.
-JSP allows to emphasize upon presentation using Java capabilities but without writing a Java code.
-It looks more like HTML and less like Java.
-When the JSP is requested for the very 1st time, it is loaded by web container.
-Once the loading is finished, it is compiled and translated into servlet.
-The Java class for this servlet is also generated by web container.
-Web Container instantitates this Java class and invokes ’jspInit()’.
-Then it invokes _jspService().
-When the JSP is requested, every time _jspService() gest invoked.
-When the server stops or the application is undeployed, web container invokes jspDestroy().
-------------------------------------------------------------------------------------------------------------------------
JSP File Structure :
A JSP file may contain a following code :
1. HTML Tags
2. Any valid Java code
3. JSP Tags
JSP Tags:
JSP tags are divided into three categories :
1. Directives :
-They are denoted by ’<%@......%>’ delimiters.
-There are three types of directives :
i. page - It is used to configure JSP page with the help of several attributes.
e.g., language => used to specify scripting language. (Default : java, Possible : java)
session => used to indicate whether page participates in session or not.
(Default : true, Possible : true/false)
import => used to import libraries from packages other than java.lang
errorPage => used to divert control to this page if the current page contains some java code which
fires an exception.
ii. include - It is used to include resources in the existing JSP. It provies a ’file’ attribute to include the
resources.
iii. taglib - It is used in the context of creating custom tags (user defined tags).
2. Scripting Elements :
-These are associated with a Java code.
-They are of three types :
1. Declaration - It is denoted by ’<%! ......%>’ delimiters.
It is used to declare variables or define methods.
2. Scriptlet - It is denoted by ’<% ......%>’ delimiters.
It is used to write any valid java code.
3. Expression - It is denoted by ’<%=<<Expre>>%>’ delimiters.
It can be used for fetching variable’s value, invoking methods and so on.
-Scripting Elements concepts :
1. Whatever declarations are made using ’Declaration’ section get processed directly at the class level
of the servlet specific class generated by web container.
2. Whatever code is written inside a ’Scriptlet’ gets processed within the _jspService() method of the
servlet specific class.
If a variable is declared inside a ’Scriptlet’ it becomes a local variable to that method.
It is not possible to define a method inside a scriptlet.
3. It is possible to invoke a method using ’Expression’ only when its return type is other than ’void’.
Implicit Objects :
-In JSP, web container creates resource oriented objects and makes them available to page authors.
-These objects are called as Implicit Objects.
1. request => jakarta.servlet.http.HttpServletRequest
2. response => jakarta.servlet.http.HttpServletResponse
3. out => jakarta.servlet.jsp.JspWriter
4. session => jakarta.servlet.http.HttpSession(Not available if <%@page session="false"%>
5. config => jakarta.servlet.ServletConfig
6. application => jakarta.servlet.ServletContext
3. Standard Actions :
-JSP specifications provides wide range of tags meant for handling standard operations; therefore these
tags are also called as Standard Actions.
-All JSP Standard Actions follow a specific format :
<prefix:suffix>
-All JSP Standard Actions have same prefix : ’jsp’.
-The ’suffix’ is the actual tag name.
1. <jsp:useBean>
-Allows to instantiate a Java Bean.
-It provides several attributes :
a) id : Assigns an identity for the bean.
b) class : Specifies fully qualified name of the bean class.
c) type : Specifies fully qualified name of the super class or an interface.
d) scope : Specifies the scope of the bean Possible Values : page, request, session, application.
Default : page
2. <jsp:setProperty>
-Allows to set values for the properties of the bean using setter methods.
3. <jsp:getProperty>
-Allows to get values of the properties of the bean using getter methods.
When <jsp:setProperty> standard action is used with setting : property="*", web container retrieves
request parameter name and tries to match them with property names of the bean class.
-Once the match is found, container tries to find setter methods in the bean class following Java’s naming
convention.
-Once the methods are found, container invokes them.
-Whatever type conversion is required, that is also managed by web container.
When <jsp:getProperty> standard action is used, web container retrieves the property name and tries to
find getter methods following Java’s naming convention.
-Once found, it invokes them.
3. <jsp:param> : Used to conjuction with either ’forward’ or ’include’ to send additional parameters.
e.g., <jsp:forward page="next.jsp" >
<jsp:param name="..." value="..." />
<jsp:param name="..." value="..." />
</jsp:forward>
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Java Frameworks : (30-11-2024)
-In the context of Java Programming Model, technologies are mainly divided into two types :
1. Specification :
-It provides a set of rules but not the implementation.
-The actual implementation is provided by third-party softwares known as Web Server and Application
Server.
e.g., Jakarta EE is a specification which is implemented by Web Server and Application Server.
2. Framework :
-It is a partial solution or an implementation used to address common problems.
-It provides its own library and a workflow.
-There are so many frameworks based upon Java technology available.
-Every frameworks has its own significance.
e.g., JUnit is framework meant for Unit Testing.
EasyMock is meant for mocking.
-There are two frameworks which are very popular and used frquently in Java bases projects :
1. Hibernate
2. Spring
-------------------------------------------------------------------------------------------------------------------------
Hibernate :
-What is Hibernate?
Hibernate is an open source Java based framework meant for building Persistence Layer of an
application. (refer hibernate diagram...)
-Why Hibernate?
Although JDBC can resolve the problem of data persistency, it involves certain challenges :
1. A lot of boiler-plate code.
2. Must make use of SQL always.
3. For performance optimization, extra efforts are required because it’s not built-in available.
4. A lot of code required for handling CRUD operations.
-These challenges can be overcome using Hibernate.
-What is ORM?
-ORM stands for Object to Relational Mapping.
-It is a set of principles meant for mapping a domain specific objects to relational database tables with
the help of mapping metadata.
-Principles of ORM :
1. Automated Persistence : Very less code for CRUD operations.
2. Full Support for Object Modeling : Provides support for Containment and Inheritance.
3. Full Support for Performance Optimization : Provides performance optimization techniques like :
fetching, caching, etc,..
4. Full Support for Query Language : Provides a query language that is tailored to work upon classes
and their properties rather than tables and columns.
-Any framework which follows all these principles, is called as an ORM framework.
e.g., Hibernate
Toplink
EclipseLink
IBatis
-Hibernate Core API :
-The core API of Hibernate mainly consiste of following :
1. Session :
-It is an interface from ’org.hibernate’ package.
-It is a short-lived light-weight object meant for handling Data Persistency(CRUD).
-It is an abstraction on the top of JDBC Connection.
2. SessionFactory :
-It is an interface from ’org.hibernate’ package.
-It is a long-lived heavy-weight object meant for obtaining a session..
-It is recommended to have only one per application.
3. Configuration :
-It is a class from ’org.hibernate.cfg’ package.
-It is used to configure Hibernate based upon metadata.
-The metadata is of two types :
a. Mapping Metadata :
-It is a metadata used to provide mapping between class and table, field and column and so on...
-There are two ways to provide mapping metadata :
i. Using XML file
ii. Using Annotations
-If it is done using XML file, that XML file is turned as HBM(Hibernate Mapping) file.
b. Configuration Metadata :
-It is a metadata used to provide JDBC configuration properties for connecting to databases.
-Hibernate uses this properties for establishing connection with database.
-There are three ways to provide configuration metadata :
i. Properties File (.properties (name=value pairs))
ii. XML File
iii. Java Code (Programmatically)
-If it is done using XML file, that XML file is turned as CFG(Configuration) file.
4. Transaction :
-It is an interface from ’org.hibernate’ package.
-It is used to manage the transactions by maintaining atomicity.
-It is especially required for DML operations.
5. Query :
-It is an interface from ’org.hibernate.query’ package.
-It is used to perform query operations using some query lannguage that makes use of classes and
their properties and not tables and their columns.
-------------------------------------------------------------------------------------------------------------------------
Getting Started :
Step 1 : Install hibernate specific library.
-In order to get started with Hibernate, it is necessary to install Hibernate specific library.
-This library is a collection of several classes, interfaces, annotations, and so on., i.e. bundled together
using several JAR files.
-These JAR files must be downloaded from internet.
-This can be done by two ways :
1. Download them manually
2. Download them using some build tools like Maven or Gradle.
Using Maven :
-Create a Maven based simple Java Project.
-Setup the environment for version 17+
a. JRE
b. Java Compiler
c. Project Facets for Java
-Add Hibernate specific dependency
Step 2 : Provide an entity class.
-In the context of Hibernate, the class of which object’s data persisted in database table as a record, is
referred as an Entity class.
Step 3 : Provide a HBM file(Mapping file)
-The entity class needs to be mapped with database table.
-Its field need to be mapped with columns.
-This can be done using a mapping file which is HBM file.
-It’s an XML file and can have any name but by convention it is as per the following format :
[Entity-Class-Name].hbm.xml
-This file must be kept under ’src/main/resources’ folder.
Step 4 : Provide a CFG file(configuration file)
-In order to establish connection with database, hibernate needs configuration setup.
-This can be done using a configuration file which is a CFG file.
-This is an XML file and by default, Hibernate searche for this file with name : ’hibernate.cfg.xml’
-This file must be kept under ’src/main/resources’ folder.
Step 5 : Write a main program
-Configure Hibernate using ’Configuration’ class.
-Obtain a SessionFactory using ’Configuration’ class.
-Obtain a session using SessionFactory.
-Create an entity class object.
-Obtain a transaction and start the same.
-Store the entity class object using Session.
-Commit the transaction.
-Close the Session.
-Close the SessionFactory.
-------------------------------------------------------------------------------------------------------------------------
Hibernate Application Workflow :
-When the object of configuration class is created, Hibernate starts searching for a configuration file :
hibernate.properties.
-If found, loads the entries from that file.
-Many times, XML file is preferred insted of .properties file.
-Therefore to intimate about XML file, ’configure()’ method is used.
-When this method is called, Hibernate searches for the file : ’hibernate.cfg.xml’
-If the name of the XML file is other than ’hibernate.cfg.xml’, an overloaded configure method is to be
used.
-Once hibernate is configured based upon configuration and mapping metadata, a SessionFactory is to
be obtained.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Implementing Standard Practices :
-It is always better to follow standard practices.
1. Auto-Loading of JDBC Driver.
2. Open SessionFactory and Session using try-with resources so that they get closed automatically.
3. Decouple the code of obtaining SessionFactory using a seperate class.
-Mapping Metadata :
-In case of mapping metadata, Hibernate supports annotations.
-There are two types of annotations :
1. Hibernate Annotations : These are the annotations explicitly provided by Hibernate for handling
mapping metadata.
2. JPA Annotations : JPA stands for Jakarta Persistence API (Java Persistence API)
-It is a specification which is implemented by any ORM framework. e.g., Hibernate, Toplink,..
-JPA provides its own set of annotation known as JPA annotation.
-Configuration metadata:
- In case of configuration metadata, hibernate supports programmatic approach using ’configuration’
class.
- It provides relevant methods to add the properties:
1. setProperty(String, String)
[names of the property] [value of the property]
2. setProperties(java.util.Properties)
3. Detached :
-The persistence context with which the entity was associated, if that context is closed, the entity goes
into ’Detached’ state.
4. Removed :
-When the entity is explicitly removed using ’remove()’ method, it results into deletion of the record from
the database table.
-In this case, the entity is said to be in ’Removed’ state.
-------------------------------------------------------------------------------------------------------------------------Working with
Session : (01-12-2024)
-The object of type ’Session’ is always required for handling CRUD operations. Therefore it is the
persistence context of the application.
-It provides relevant methods :
persist() => Used for DML INSERT
find() => Used for SELECT
remove() => Used for DML DELETE
(No seperate method for DML UPDATE because it is handled using setter methods and Transaction’s
commit() )
-Sometimes, there are long running transactions and therefore it is better to close the session if the
transaction is taking some time.
-When the session is closed, the loaded entity object which was in the Persistent state, goes into
Detached state.
-End user can make changes into this object by calling setter methods.
-This changes the state of the entity object but not database.
-In order to change the database state, it is necessary to reflect the entity state back to databse.
-This is possible only if the entity object is in Persistent state.
-Therefore it is necessary to bring the Detached entity back into Persistent state.
-This is possible using ’merge()’ method of ’Session’ interface.
e.g., Session s1 = ...
Movie m1=s1.find(...); //m1 goes into Persistent state.
s1.close(); //m1 goes into Detached state.
-One to One :
-In this, an entity holds a single reference of another entity.
-In database, any table may contain a Foreign Key column.
e.g., Relationship between Employee and Passport.
-Many to Many :
-In this an entity holds references of another entity.
-In database, a 3rd table(Junction Table or Join Table) is required.
-It contains Foreign Key columns referring to both the entity specific tables.
e.g., Relationship between Employee and Certification.
-Unidirectional Associations :
-In this case one entity holds reference or references of another entity; but the 2nd entity does not hold
any reference back to 1st.
-Bidirectional Associations :
-In this case, both the entity holds reference or references of each other.
----------------------------------------------------------------------------------------------------------------------
Querying the database :
-In business applications, retrieving multiple records from database table is a very frequent requirement.
-Hibernate’s Session interface provides a find() method to retrieve the data from the database table.
-However, find() method has 1 limitation : It can retrieve only one record that is based upon identity.
-Therefore, in order to retrieve multiple records, Hibernate provides a Query Language known as HQL.
2. SELECT :
-It is used to load the selected data.
-It reduces the memory overheads.
-It returns a collection holding elements of type ’array’ of type ’Object’.
-------------------------------------------------------------------------------------------------------------------------
Using Constructor Expression :
-It is a mechanism that allows to instantiate a Java bean using a constructor through the query string.
-It simplifies the working of SELECT clause.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Spring : (02-12-2024)
-What is Spring ?
-Spring is a java based framework used to handle various aspects of the application.
-It is not intended for doing only one thing, rather it can handle several things.
-Spring can be used to handle different types of requirements.
e.g., Integrating enterprise services (Higher-end Services)
-Spring Modules :
-Spring can handle different types of requirements of the application through several modules.
-There are so many modules involved in Spring :
1. Spring Core :
-This is the module present at the bottom level.
-It is meant for handling core functionalities of Spring.
-It is the base for all the other modules.
2. Spring AOP :
-AOP stands for Aspect Oriented Programming.
-It is a module which allows applications to seperate secondary concerns from primary concerns.
3. Spring Data Access :
-Spring does not attempt to provide its own implementation for accessing the data from databse; rather
it provides hooks(adapters/connectors) for integrating with other persistence oriented technologies like
JDBC, Hibernate, JPA, etc.
4. Spring MVC :
-MVC stands for Model View Controller.
-It is a commonly used architecture or design pattern for building web based applications.
-This module is used to build web based applications.
5. Spring REST :
-REST stands for Representational State Transfer.
-It is a type of web service for building APIs.
-Spring provides awesome support for building Restful APIs as back-end services using this module.
6. Spring Security :
-This module allows to secure the applications.
-Typically third is done at two levels :
Authentication and Authorization
7. Spring Cloud :
-Spring provides support for deploying the back-end services in the cloud using this module.
-It provides a large eco-system to manage cloud specific functionalities.
-------------------------------------------------------------------------------------------------------------------------
Spring Core :
-It is the module persent at the base.
-It handles core functionalities of Spring.
-It mainly provides two functionalities :
1. Bean Management
2. Dependency Injection
Bean Management :
-Like Jakarta EE, Spring is also based upon component driven Architecture.
-Typically, in Java SE, components are unmanaged but they are independent (POJOs) whereas, in
Jakarta EE, components are managed but they are dependent (Non-POJOs).
-Spring offers a dual service. It can manage the life cycle of the components even though they are
simple POJOs i.e. independent.
-The component that is to be managed by Spring, must be registered with the environment of Spring.
-Any component that is registered with the Spring’s environment is called as a Spring Bean.
-------------------------------------------------------------------------------------------------------------------------
Getting Started :
Step 1 : Install Spring Specific library
-Like Hibernate, Spring is also a framework and therefore its library is distributed in the form of JAR
files.
-To get started with Spring, it is necessary to download these JAR files.
-This can be done by 2 ways :
1. Download them manually from Internet.
2. Resolve them using some build tools like Maven or Gradel.
Step 4 : Register or declare the bean of this class type with Spring’s environment :
-In order to register any component as a bean with Spring’s environment, Spring provides a
configuration unit.
-A configuration unit is a place where beans are registered or declared.
-There are two ways to provide this configuration unit :
1. Using XML
2. Without using XML
-In case of XML option, the file can have any name but their convention it is spring-config.xml.
-This file can be placed anywhere may be inside the project or even outside the project as well.
-However, as per the standard practice, it has to be placed under : src/main/resource.
ClassPathXmlApplicationContext :
-It allows to load the context from an XML file located in the project’s CLASSPATH.
-If the file is located under src/main/resources it automatically gets added into project’s classpath.
-------------------------------------------------------------------------------------------------------------------------
Dependency Injection :
-A bean registered in Spring’s environment may have some dependencies in the form of properties.
-When a client program makes a request to Spring for getting that particular bean which has
dependencies, Spring has to inject values for those dependencies and return that bean back to the client
program.
-This process of injecting values for dependencies is known as Dependency Injection.
-Dependency Injection (DI) is also known as Inversion of Control (IOC) because the control is shifted
from client program to the Spring’s environment i.e. container.
-Spring can inject the dependencies by two ways :
1. When the client program makes a request to Spring for the bean, Spring injects values into the
properties of the bean using setter methods. This is known as Setter Injection.
2. When the client program makes a request to Spring for the bean, Spring injects values into the
properties of the bean using parameterized constructor. This is known as Constructor Injection.
-In case of Constructor Injection, by default the order of the arguments is taken from top to bottom in
XML and left to right in Java.
------------------------------------------------------------------------------------------------------------------------
Bean Wiring :
-Sometimes, a bean is dependent upon another bean and that another bean may further depend upon
some other bean and so on...
-When a client program makes a request to Spring for the main bean, Spring has to wire all its dependent
beans and then returns the main bean back to the client.
-In this case, Spring has to build the inner-most bean first and keep gradually building outer beans and
finally building outer-most bean and return it back to the client program.
-This entire process is known as Bean Wiring.
-In order to perform Bean Wiring at XML level, there are 2 options :
1. Using ’ref’ attribute.
1. Using ’<ref>’ element.
------------------------------------------------------------------------------------------------------------------------
Bean Loading :
-Whatever bean is registered in Spring’s configuration unit, gets instantiated by Spring.
-The process of instantiating the bean is known as Bean Loading.
-In Spring, bean loading takes place by two ways :
1. EAGER :
-This is the behaviour spring follows by default.
-When the context is loaded, Spring starts instantiating the beans available in the configuration unit
even though they have not been requested by the client program.
-This is known as EAGER loading.
2. LAZY :
-In this case, Spring creates an object of the bean class only when a client program makes a request
for the bean of that type.
-This is known as LAZY loading.
-It is enabled using [lazy-init = "true"] setting for ’<bean>’ element.
-Both these strategies are to be used based upon the requirement.
-If the bean is light-weight, it is fine if it gets instantiated on startup whereas if it is heavy-weight, ideally it
must be instantiated only when the client program makes a request for it; otherwise it consumes the heap
memory unnecessarily.
------------------------------------------------------------------------------------------------------------------------
Bean Scope :
-Every bean registered in Spring’s configuration unit has some scope.
-There are five possible scopes available :
1. singleton :
-It is the default scope of the bean.
-If the same bean is requested multiple times, Spring returns the same object. It does not create new
object every time.
2. prototype :
-It is exactly opposite to singleton.
-If the same bean is requested multiple times, Spring returns a new object every time.
-To specify the scope, use ’scope’ attribute of ’<bean>’ element.
-The scope that is to be used is requirement specific.
-Especially, if the bean contains some configuration specific data, ideally its scope will be ’singleton’
whereas if it contains some domain specific data, the ’prototype’ will be appropriate.
3. request :
-It is applicable in Spring MVC environment only.
-In this case, the bean is associated with an object of type: jakarta.servlet.http.HttpServletRequest.
4. session :
-It is applicable in Spring MVC environment only.
-In this case, the bean is associated with an object of type: jakarta.servlet.http.HttpSession.
5. global-session :
-It is applicable in Spring Portlet environment.
------------------------------------------------------------------------------------------------------------------------
Task :
Create a class EducationInfo with following attributes :
highestDegree (String)
grade (String)
Create a class ContactInfo with following attributes :
mobileNo (String)
emailAddress (String)
Create a class Profle with following attributes :
candidateId (int)
name (String)
contactDetails (ContactInfo)
educationDetails (EducationInfo)
AOP Terminologies :
In Spring AOP, there are five terminologies used :
1. Advice : It defines WHAT and WHEN of an aspect.
2. JoinPoint : It is the probable location where an aspect CAN BE plugged in.
3. PointCut : It is the exact location where an aspect IS TO BE plugged in.
It advice defines WHAT and WHEN, then point cut defines WHERE.
4. Aspect : It is the merger of Advice and PointCut.
It defines WHAT, WHEN and WHERE.
5. Proxy : -It is the mediator between a client program and the target bean
-When a client program makes a request, proxy comes in between and intercepts that request.
-Similarly, when the target bean method execution is over, proxy comes in between and intercepts that
call as well.
-Spring has a special container to manage all these things.
-It is called as AOP container.
-It is responsible for handling all the activities relevant to AOP.
-It is also responsible for proxy generation.
-The process generation of proxy generation is known as Weaving.
-In general, Weaving is of three types :
i. Compile Time : Proxy gets generated when the target class is compiled.
ii. Class Load Time : Proxy gets generated when the target class is loaded.
iii. Runtime : Proxy gets generated during the execution i.e. at runtime.
-In case of Spring AOP, weaving always happens at runtime.
-------------------------------------------------------------------------------------------------------------------------
Types of Advice: (04-12-2024)
-In Spring AOP, there are five types of Advice :
1.Before Advice : It is used to handle the functionality before the execution of target bean method.
2. After Returning Advice : It is used to handle the functionality after the successful execution of target
bean method.
3. After Throwing Advice : It is used to handle the functionality when the target bean method throws
some exeception.
4. After Advice : It is used to handle the functionality irrespective of whether the target bean method
executes successfully or not.
5. Around Advice : It is not meant for handling any separate functionality; rather it is a combination of all
the above four mentioned advices.
-------------------------------------------------------------------------------------------------------------------------
AOP support in Spring :
-In Spring Framework, AOP is supported by a third party library known as AspectJ.
-It is a library that is associated with Spring right from the 1st version.
-It provides several annotations for implementing AOP :
1. @Aspect : It is to be applied at the class level to indicate that the class is an aspect.
2. @Before : -It is to be applied at the method level.
-Causes the method to be invoked before the execution of the target bean method.
3. @AfterReturning : -It is to be applied at the method level.
-Causes the method to be invoked after successful execution of the target bean method.
4. @AfterThrowing : -It is to be applied at the method level.
-Causes the method to be invoked when the target bean method throws an exception.
5. @After : -It is to be applied at the method level.
-Causes the method to be invoked irrespective of whether the target bean method executes
successfully or not.
6. @Around : -It is to be applied at the method level.
-It is used to configure method as an Around Advice.
7. @Pointcut : -It is to be applied at the method level.
-It is used to declare the pointcut expression.
-The corresponding method is just used as a marker method and it is meant for forward referencing.
-------------------------------------------------------------------------------------------------------------------------
Enabling Proxy Generation :
-While working with AOP, there is always a mediator that intercepts the request and handles the aspect
specific logic i.e. a secondary concern or a cross cutting concern.
-This mediator is known as a proxy and Spring AOP container is responsible for generating it.
-However, this proxy generation takes place only when the relevant support is enabled.
-This is done by using annotation : @EnableAspectJAutoProxy
-It is to be applied at the class level of the configuration specific class.
-------------------------------------------------------------------------------------------------------------------------
Getting Started:
Step 1:
-Install the third-party library i.e AspectJ specific JAR Files.
-This is done by adding 2 dependencies:
1. aspectjweaver
2. aspectjrt
Step 2 : Create target bean class and declare it as a managed component : This is the class which
defines primary concerns.
Step 3 : Create an aspect specific class : This is the class which defines secondary concerns.
-In order to intimate Spring that the class is an aspect specific class, it must be annotated with @Aspect
annotation.
-Defining the secondary concerns using relevant methods.
-Configure these methods as advices using relevant annotations.
-Once it is done, it specified WHAT and WHEN but not WHERE.
-This is done using a point-cut expression.
-The point-cut expression provides several designators .
e.g., execution
within
args...
-The point-cut expression can be mentioned directly as a String parameter for the advice specific
annotations.
-However, this option is not recommended beacuse if any change is required, e.g., if the package name
is changed, the changes must be done at all places where the expression is used.
-Therefore, the better option is to define a method and mark that method as a point-cut.
-This method just acts as a marker method and it does not participate in any execution; rather it is just
used fro forward referencing.
-Since the method specifies the point-cut expression, it must be annotated with @Pointcut annotation.
-What is MVC ?
-MVC stands for Model-View-Controller.
-It is a commonly used architecture or a design pattern for building Web Based Applications.
-Model :
-It is the responsible for handling the business logic of the application.
-It is also responsible for storing application specific data.
-Generally, it is implemented using a simple Java class(Java Bean) or an EJB(Enterprise Java Bean).
-View :
-It is responsible for handling presentation logic of the application.
-It either accepts the data from the end user or presents the data to the user.
-Generally it is implemented using HTML and JSPs.
-Controller :
-It is responsible for handling the navigation and the workflow of the application.
-It is used to bridge the gap between model and view.
-Generally, it is implemented using Servlets.
-This is why Jakarta EE has 3 components keeping MVC in mind : Servlet(Controller), JSP(View) and
EJB(Model).
2.MVC 2-
-In this case, all the three aspects: Model, View and Controller are decoupled from each other.
-Model is taken care by java class (java bean) or EJB, view is by JSP and controller is by servlet.
-Since the entire navigation and workflow is handled using servlet, this architecture is called as Servlet
Centric Architecture.
-Since is follows code separation, it is highly recommended.
Step 10 : Open the client (Web Browser) and hit the URL.
-------------------------------------------------------------------------------------------------------------------------
Spring MVC Application Workflow :
-When the application is deployed on web server and the server is started, the ’onStartup()’ method from
WebApplicationInitializer implementation class gets called.
-This method is used to configure following things :
1. The base package for component scanning
2. The front controller DispatcherServlet
-Due to the base package for component scanning activity, all the classes annotated with Spring’s stereo
type annotations, e.g., @Component, @Controller and so on.., falling under that package get scanned.
-Since the controller class contains a request handling method annotated with @RequestMapping
annotation, that also gets scanned.
-When the application is requested for the very 1st time, the implementation class of WebMvcConfigurer
gets triggered and the view resolver gets configured, precisely it is : InternalResourceViewResolver based
upon prefix and suffix.
-Since every URL starts with a ’/’ and the front controller that is DispatcherServlet is already configured
with that particular URL mapping, every time first the request hits this front controller.
-After this, based upon the actual URL (/doGreet), the front controller delegates the call to the controller
by invoking the request handling method (getIndexPage()).
-This method is actually used to handle the request.
-This method either handles the request of its own or delegates the call to the model.
-Eventually, it returns a view name back to the Front Controller.
-Front Controller receives the view name returned from Controller and resolves th e actual view with the
help of some view resolver known as InternalResourceViewResolver.
-It resolves the view based upon two properties : prefix and suffix.
-Eventually, it renders the actual view back to the client.
-------------------------------------------------------------------------------------------------------------------------
HTML Form Processing :
-A web application accepts data from end user using some HTML form and that data needs to be
processed further.
-This is called as HTML Form Processing.
-In Spring MVC, unlike servlet, methods : doGet() and doPost() are not available.
-Therefore, handles for the ojects of type 'HttpServletRequest' and 'HttpServletResponse' are also not
available.
-In this case, in order to fetch request specific parameters, a parameterized request handling method is
used.
-Further to store the values in the receiving variables, it is necessary to bind request specific parameters
with these receiving variables.
-This is done using @RequestParam annotation.
-It is to be applied at the receiving parameter level.
-In case of form processing, ideally HTTP POST request is sent as GET request has security
implications.
-Therefore, the request handling method must be configured in such a way that it handles the POST
request.
-This is done by specifying 'method' attribute for @RequestMapping annotation.
-------------------------------------------------------------------------------------------------------------------------
Rendering application specific data :
-When the request is processed and the response is generating in the form of some view, it might be
required to render application specific data in the resultant page.
-In order to render the data in the resultant page, first the data must be stored somewhere.
-The container where this data gets stored is called as Model object.
-In order to work with this Model object, Spring MVC provides an interface : Model
-In order to use 'Model' interface it is necessary to declare a receiving parameter of that type in request
handling method.
-In order to store data in the Model object, 'Model' interface provides relevant methods, e.g.,
addAttribute()
-Once the attribute is added in the Model object, by default it is in the REQUEST scope.
-Sometimes, this data needs to be used accross multiple request made within a session and therefore,
ideally it must be kept in a SESSION scope.
-This is possible using @SessionAttributes annotation.
-It is to be applied at the class level.
-------------------------------------------------------------------------------------------------------------------------
Simplifying Request Mapping :
-In order to configure method for handling the request, Spring MVC provides @RequestMapping
annotation.
-It is the single annotation that is used to handle various types of HTTP requests.
-As long as GET request is to be configured, it is simple as it is the default type taken into consideration.
-In case of other requests, a special 'method' attribute needs to be mentioned.
-This can be simplified using relevant HTTP method oriented annotations.
e.g.,
GET => @GetMapping
POST => @PostMapping
PUT => @PutMapping
DELETE => @DeleteMapping
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Task :
-Build a web application that allows end user to manage Cricket Team data as per the following :
Cricket Team
teamId (String)
teamName(String)
testRanking (int)
odiRanking (int)
t20Ranking (int)
-The data about Cricket Team is maintained using some in-memory collection with the help of some Java
class.
-The application starts with a home page that is accessed using '/home' end point.
-The home page must show 2 hyper links :
i. Add Cricket Team
ii. View Cricket Team
-When the 1st link is clicked, a page must be rendered showing HTML form for accepting user input
about the team along with submit button.
-When submit button is clicked, the application must store team data into in-memory collection and
render the home page back to the client.
-When the 2nd link is clicked, a page must be rendered which shows HTML form asking for team ID
along with submit button.
-When submit button is clicked, the application must search for the team against ID into in-memory
collection and render the details of that team in the result page.
-The result page must display appropriate message if the team ID is invalid.
-The result must also provide a hyper link so that user can click the same and come back on home page.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Spring REST : (6-12-2024)
-Spring Framework provides a module Spring REST that is used for building REST APIs.
2. Restful :
-In the last 7 to 8 years, one more type of web service is in used and it got wide acceptance due to its
simplicity.
-It is called as Restful Web Service.
-It emphasized upon informatio-centric architecture.
-It is completely based upon plain HTTP protocol.
-The resource which contains an information is reffered as REST resource.
-The URL that is used to work with REST resources is called as REST End point.
-Understanding REST :
-REST stands for Representational State Transfer.
-Representational :
-It emphasizes upon representing the state of the resource.
-When a client makes a request for some data, server accepts the request and populates a data from
some data store.
-Assuming the technology used for building REST API is Java, the populated data is stored inside a
Java object.
-That data is sent back to client along with HTTP response.
-The client consumes that data in any format which is suitable to the client itself.
-There are several formats in which data can be consumed but the most commonly used format is
JSON.
-JSON stands for Java Script Object Notation.
-It is a format which can be easily processed using Java Script oriented technologies.
e.g., Plain Java Script (Vanilla JS)
Angular
React
Vue JS
-State :
-It encapsulates current values available in the resource.
-The state of the resource is populated on one side and made available on another side.
-Transfer :
-The state populated on one side is to be made available on another side. This is done by using
Transfer operation.
-If it is populated on server, it is transferred towards client via HTTP response.
-If it is populated on client, it is transferred towards server via HTTP request.
-------------------------------------------------------------------------------------------------------------------------
Implementing REST API :
-Since REST APIs are completely based upon HTTP protocol and like SOAP based web services they
are inter-operable, they can be implemented using any technology like : Java, .net, python and even
NodeJS.
3. Spring Initializer :
-It is a web interface used to configure Spring Boot project online and then it allows to download the
same and further that project can be used to implement REST API.
-------------------------------------------------------------------------------------------------------------------------
Getting started with Spring Boot :
Step 1 : Open web browser and access Spring Initializer using URL : 'start.spring.io'
Step 2 : Enter all the project specific details e.g., Type, Language, Spring Boot Version,
Metadata(GroupID, ArtifactID). Select dependencies (Web, Devtools) and click "Generate" to download
the zip file.
2. Spring Application :
-It is a class that is used to bootstrap the application.
-It is used to launch an embedded Tomcat on a default port number : 8080
-It is done using its 'static' method : run()
-It is possible that the class which is annotated with @SpringBootApplication annotation and the class
which contains main() method for bootstraping, are different.
e.g., @SpringBootApplication
public class AppConfig { ... }
-When a REST client makes a request towards REST API, it is necessary to interact with data store for
handling various operations.
-In order to have a code separation, ideally it should take place using a Layered Architecture.
-The layered architecture consists of three layers :
1. Controller Layer :
-It is the layer responsible for interacting with REST client.
-It accepts the request from REST client and generates the response.
-It acts as a client of Service Layer.
2. Service Layer :
-It is the layer responsible for handling business logic if any.
-It acts as a client of Repository Layer.
-It also acts as a bridge between Controller and Repository Layer.
3. Repository Layer :
-It is the layer responsible for interaction with data store.
-It performs all the required data persistency related operations.
2. Partial Update :
-In this case, some of feild values except ID are updated.
-This is implemented by making HTTP PATCH request.
-In case of Spring Data JPA, irrespective of whether it is POST, PUT or even PATCH, the JpaRepository
provides a common method : save()
-Actually, this method is meant for performing UPSERT operation.
-------------------------------------------------------------------------------------------------------------------------
Working with HTTP Response :
-In case of REST, the API must be implemented keeping the consumer in mind.
-When a client makes a request, server accepts the same and generates the response. Ideally server
must generate a proper response back to the client based upon which a client can take necessary action.
-This is done by sending the appropriate response status.
-Spring provides a relevant annotation to configure the response status : @ResponseStatus
-------------------------------------------------------------------------------------------------------------------------
Spring Security :
-In any enterprise application, security plays an important role .
-Different types of technologies have their own security model.
-However up to certain extent, all the technologies implement security model using basic standards.
-Typically, the security is handled at two levels :
1. Authentication :
-It is the 1st step of security.
-It decides whether a user is allowed to enter into the application or not.
-Typically, it is handled using credentials like username and password.
2. Authorization :
-Once a user is authenticated, depending upon the requirements, certain privileges are granted to the
users.
-This is called as authorization.
-In order to handle authentication and authorization, mainly 2 entities are used :
1. Users :
-These are the actual users of the application.
-There might be several users within the application i.e. the user count is not fixed.
2. Roles :
-These indicate the authority given to the specific user.
-A single user may have multiple roles similarly a single role can be played by multiple users.
-The actual role varies from application to application.
-In a specific application the role count is fixed.
-When the Spring Boot project with Web and Security dependencies is created, by default Spring
Security Model implies authentication on all URLs.
-It implies authentication not only for existing URLs but also for non-existing URLs.
-By default, Spring Security is configured with a single user where the username is 'user' itself and the
password is randomly generated password which is available in the server logs.
-By default, Spring Security provides four things :
1. /login URL
2. /logout URL
3. Login Form
4. Logout Form
------------------------------------------------------------------------------------------------------------------------
Customizing Spring Security :
-The default credentials (username and password) provided by Spring Security are just meant for
development purpose.
-They are not recommended in production environment.
-Therefore, applications need to configure security model as per the requirement.
e.g., By default, Spring Security secures every URL and in actual application it may not be required.
-In order to customize Spring Security, there is predefined API available : SecurityFilterChain
-Spring Security no. of filters which are meant for intercepting the request. These filters executes in a
specific manner which is known as a filter chain.
-Therefore, in order to customize Spring Security, it is necessary to configure a bean of type
SecurityFilterChain.
-Once the SecurityFilterChain is configured for customization, it is necessary to enable that
configuration.
-This is done by using @EnableWebSecurity annotation.
-It is to be applied at class level.
-In order to customize Spring Security, there are relevant APIs available : HttpSecurity and Customizer
-In Security customization, once the roles are configured for URLs, it is necessary to configure users to
assign roles to them.
-These users are available in some repository.
e.g., In-Memory
Database
LDAP
-To configure users, there is a seperate API which consists : UserDetails, User and
UserDetailsInService.
-In Spring Security, the security model enforces to encode the passwords.
-This can be done by different encoding algorithms.
e.g., BCryptPasswordEncoder
-To use password encoding, it is necessary to configure the bean of that type.
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=