Spring Boot Tutorial Part 1
Spring Boot Tutorial Part 1
If the number of clients increases, it takes more time for sending the
response.
For each request, it starts a process, and the web server is limited to start
processes.
It uses platform dependent language e.g. C, C++, perl.
Servlet
Servlet technology is used to create a web application (at server side and
generates a dynamic web page).
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for handling
the multiple requests to the Servlet. Threads have many benefits over the Processes such as they
share a common memory area, lightweight, cost of communication between the threads are low.
The advantages of Servlet are as follows:
Better performance: because it creates a thread for each request, not process.
Portability: because it uses Java language.
Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
Secure: because it uses java language.
Servlets - Life Cycle
https://www.javatpoint.com/servlet-tutorial
https://www.tutorialspoint.com/servlets/index.htm
Environment Setup
Cookies: are text files stored on the client computer and they are kept for
various information tracking purpose. Java Servlets transparently supports HTTP
cookies.
There are three steps involved in identifying returning users:
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
Advantage of Cookies:
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies:
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Difference between Cookies and Session
Session Cookies
A session stores the variables Cookies are stored on the user's
and their values within a file in a computer as a text file.
temporary directory on the server.
The session ends when the user Cookies end on the lifetime set by
logout from the application or the user.
closes his web browser.
It can store an unlimited amount It can store only limited data.
of data.
We can store as much data as The maximum size of the
we want within a session, but browser's cookies is 4 KB.
there is a maximum memory limit,
which a script can use at one
time, and it is 128 MB.
Sessions are more secured Cookies are not secure, as data
compared to cookies, as they is stored in a text file, and if any
save data in encrypted form. unauthorized user gets access to
our system, he can temper the
data.
Static vs Dynamic website
It uses the HTML code for developing a website. It uses the server side languages such as PHP,SERVLET,
JSP, and ASP.NET etc. for developing a website.
It sends exactly the same response for every request. It may generate different HTML for each of the request.
The content is only changed when someone publishes and The page contains "server-side" code which allows the
updates the file (sends it to the web server). server to generate the unique content when the page is
loaded.
Flexibility is the main advantage of static website. Content Management System (CMS) is the main advantage
of dynamic website.
Static vs Dynamic website
Web Terminology
1) In case of Get request, only limited amount of data can In case of post request, large amount of data can be sent
be sent because data is sent in header. because data is sent in body.
2) Get request is not secured because data is exposed in Post request is secured because data is not exposed in URL
URL bar. bar.
4) Get request is idempotent . It means second request will Post request is non-idempotent.
be ignored until response of first request is delivered
5) Get request is more efficient and used more than Post. Post request is less efficient and used less than get.
Web Server vs. Application Server
Web Server: Web server contains only web or servlet container. It can be used for servlet,
jsp, struts, jsf etc. It can't be used for EJB (Apache Tomcat, Resin).
Web Server Working: It can respond to the client request in either of the following two
possible ways:
Generating response by using the script and communicating with database.
Sending file to the client associated with the requested URL.
Important points:
If the requested web page at the client side is not found, then web server will sends the HTTP
response: Error 404 Not found.
When the web server searching the requested page if requested page is found then it will send to the
client with an HTTP response.
If the client requests some other resources then web server will contact to application server and
data is store for constructing the HTTP response.
Application Server
Application server: contains Web and EJB containers. It can be used for servlet,
jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-
tier of a server centric architecture.
The Example of Application Servers are:
JBoss: Open-source server from JBoss community.
Glassfish: Provided by Sun Microsystem. Now acquired by Oracle.
Weblogic: Provided by Oracle. It more secured.
Websphere: Provided by IBM.
Difference Between JAR WAR and EAR
JAR file: is a file with Java classes, associated metadata and resources such as text,
images aggregated into one file (Java Archive).
WAR file: is a file that is used to distribute a collection of JAR files, JSP, Servlet,
XML files, static web pages like HTML and other resources that constitute a web
application. Thus, this explains the main difference between JAR and WAR Files
(Web Application Resource).
EAR file: is a Java EE file that packs one or more modules into a single archive to
deploy them on to an application server (Enterprise Application Archive).
Spring Tutorial
Spring framework: is an open source Java platform that provides comprehensive infrastructure support for
developing robust Java applications very easily and very rapidly.
History: It was developed by Rod Johnson in 2003. Spring framework makes the easy development of JavaEE
application.
Benefits of using Spring Framework:
o POJO Based: not mandatory application server but you can using servlet container such as Tomcat
o Modular
o Integration with existing frameworks: such as Struts, Hibernate, JSP, JSF
o Testability
o Web MVC
o Central Exception Handling
o Lightweight
o Transaction management
Spring Modules
Spring is modular, allowing you to pick and choose which modules are applicable
to you, without having to bring in the rest.
This is the simplest container providing the basic support for DI and defined by the
org.springframework.beans.factory.BeanFactory interface.
There are a number of implementations of the BeanFactory interface that are come
straight out-of-the-box with Spring. The most commonly used BeanFactory
implementation is the XmlBeanFactory class. This container reads the configuration
metadata from an XML file and uses it to create a fully configured system or
application.
The BeanFactory is usually preferred where the resources are limited like mobile
devices or applet-based applications. Thus, use an ApplicationContext unless you
have a good reason for not doing so.
Application Context Container
Application Context: is Spring's advanced container. Similar to BeanFactory, it can load bean
definitions, wire beans together, and dispense beans upon request. Additionally, it adds more
enterprise-specific functionality such as the ability to resolve textual messages from a
properties file and the ability to publish application events to interested event listeners. This
container is defined by org.springframework.context.ApplicationContext interface.
The most commonly used ApplicationContext implementations are:
FileSystemXmlApplicationContext − This container loads the definitions of the beans from an XML
file. Here you need to provide the full path of the XML bean configuration file to the constructor.
ClassPathXmlApplicationContext − This container loads the definitions of the beans from an XML
file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH
properly because this container will look like bean configuration XML file in CLASSPATH.
WebXmlApplicationContext − This container loads the XML file with definitions of all beans from
within a web application.
BeanFactory vs ApplicationContext
Singleton: the container creates a single instance of that bean, all requests for
that bean name will return the same object from, which is cached (default).
Prototype: A bean return a different instance every time it is requested from
the container.
Web aware:- there are three additional scopes that are only available in a
web-aware application context.
Request: This scopes a bean definition to an HTTP request.
Session: This scopes a bean definition to an HTTP session.
Global-session: This scopes a bean definition to a global HTTP session.
Bean Life Cycle
When a bean is instantiated, it may be required to perform some initialization
to get it into a usable state. Similarly, when the bean is no longer required
and is removed from the container, some cleanup may be required.
To define setup and teardown for a bean, we simply declare the <bean>
with initmethod and/or destroy-method parameters. The init-method
attribute specifies a method that is to be called on the bean immediately
upon instantiation. Similarly, destroymethod specifies a method that is called
just before a bean is removed from the container.
Initialization callbacks: org.springframework.beans.factory.InitializingBean
interface specifies a single method
Destruction callbacks: The org.springframework.beans.factory.DisposableBean interface
specifies a single method
BeanPostProcessor interface
Starting from Spring 2.5 it became possible to configure the dependency injection
using annotations.
Annotation injection is performed before XML injection. Thus, the latter
configuration will override the former for properties wired through both
approaches.
Annotation wiring is not turned on in the Spring container by default. So, before
we can use annotation-based wiring.
@Required: applies to bean property setter methods.
@Autowired: apply to bean property setter methods, non-setter methods, constructor
and properties.
@Qualifier: along with @Autowired can be used to remove the confusion by specifiying
which exact bean will be wired.
JSR-250 Annotation: as a Java Specification Request, has the objective to define a set
of annotations that address common semantic concepts and therefore can be used by
many Java EE and Java SE components (PostConstruct, PreDestroy, Resources).
Java Based Configuration
https://www.tutorialspoint.com/spring/index.htm
https://www.javatpoint.com/spring-tutorial
Spring Boot
Spring Boot is a project that is built on the top of the Spring Framework. It
provides an easier and faster way to set up, configure, and run both simple
and web-based applications.
Advantages of Spring Boot
It creates stand-alone Spring applications that can be started using Java -jar.
It tests web applications easily with the help of different Embedded HTTP servers such
as Tomcat, Jetty, etc. We don't need to deploy WAR files.
It provides opinionated 'starter' POMs to simplify our Maven configuration.
It provides production-ready features such as metrics, health checks, and externalized
configuration.
There is no requirement for XML configuration.
It offers a CLI tool for developing and testing the Spring Boot application.
It offers the number of plug-ins.
It increases productivity and reduces development time.
Limitations of Spring Boot:-
Spring Boot can use dependencies that are not going to be used in the
application. These dependencies increase the size of the application.
A build tool is a tool that automates everything related to building the software
project. Building a software project typically includes one or more of these
activities:
Generating source code (if auto-generated code is used in the project).
Generating documentation from the source code.
Compiling source code.
Packaging compiled code into JAR files or ZIP files.
Installing the packaged code on a server, in a repository or somewhere else.
Maven Repositories
Spring Boot Dependency Management
Persistence Layer
Spring Boot JDBC
JDBC Connection Pool
HikariCP
Dependency Injection Review
Persistence layers
Any software layer that makes it easier for a program to persist its state is generically called a
persistence layer. most persistence layers will not achieve persistence directly but will use an
underlying database management system.
Spring Boot JDBC
Spring Boot JDBC provides starter and libraries for connecting an application with
JDBC.
In Spring Boot JDBC, the database related beans such as DataSource,
JdbcTemplate, and NamedParameterJdbcTemplate auto-configures and created
during the startup. We can autowire these classes if we want to use it.
In application.properties file, we configure DataSource and connection pooling.
JDBC Connection Pooling
JDBC connection pooling is a mechanism that manages multiple database connection
requests. In other words, it facilitates connection reuse, a memory cache of database
connections, called a connection pool. A connection pooling module maintains it as a layer
on top of any standard JDBC driver product.
It increases the speed of data access and reduces the number of database connections for
an application. It also improves the performance of an application. Connection pool
performs the following tasks:
Manage available connection
Allocate new connection
Close connection
HikariCP
HikariCP is a JDBC DataSource implementation that provides a connection pooling
mechanism.
It provides enterprise-ready features and better performance.
The default connection pool in Spring Boot 2 is HikariCP.
If the HikariCP is present on the classpath, the Spring Boot automatically configures it.
If the HikariCP is not found on the classpath, Spring Boot looks for the Tomcat JDBC
Connection Pool. If it is on the classpath Spring Boot, pick it up.
If both the above options are not available, Spring Boot chooses Apache Commons
DBCP2 as the JDBC connection pool.
We can also configure a connection pool manually, by exclude HikariCP dependency and
add the tomcat-jdbc dependency in the pom.xml file.
Session Content (5)
Characteristics of JSON:
JSON is easy to read and write.
It is a lightweight text-based interchange format.
JSON is language independent.
The filename extension is .json.
Dispatcher Servlet
In Spring MVC all incoming requests go through a single servlet is called Dispatcher Servlet
A single servlet receives all the request and transfers them to all other components of the application.
Jackson
Jackson is a simple java based library to serialize java objects to JSON and vice
versa.
Spring MVC and REST Annotations
@RequestMapping: It is used to map the web requests. It has many optional elements like consumes,
header, method, name, params, path, produces, and value. We use it with the class as well as the
method.
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a
web service endpoint that fetches It is used instead of using: @RequestMapping(method =
RequestMethod.GET)
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create a
web service endpoint that creates It is used instead of using: @RequestMapping(method =
RequestMethod.POST)
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a
web service endpoint that creates or updates It is used instead of using: @RequestMapping(method =
RequestMethod.PUT)
@DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It is used to
create a web service endpoint that deletes a resource. It is used instead of
using: @RequestMapping(method = RequestMethod.DELETE)
@RestController: It can be considered as a combination
of @Controller and @ResponseBody annotations. The @RestController annotation is itself annotated with
the @ResponseBody annotation. It eliminates the need for annotating each method with @ResponseBody.
@RequestBody: It is used to bind HTTP request with an object in a method parameter. Internally it
uses HTTP MessageConverters to convert the body of the request. When we annotate a method parameter
with @RequestBody, the Spring framework binds the incoming HTTP request body to that parameter.
@ResponseBody: It binds the method return value to the response body. It tells the Spring Boot Framework
to serialize a return an object into JSON and XML format.
@RequestHeader: It is used to get the details about the HTTP request headers. We use this annotation as
a method parameter. The optional elements of the annotation are name, required, value,
defaultValue. For each detail in the header, we should specify separate annotations. We can use it multiple
time in a method
@RequestAttribute: It binds a method parameter to request attribute. It provides convenient access to the
request attributes from a controller method. With the help of @RequestAttribute annotation, we can access
objects that are populated on the server-side.