Nothing Special   »   [go: up one dir, main page]

Advanced Java Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Advanced Java

MCA – II Semester
Introduction to J2EE Architecture

- The JEE platform provides the environment to develop enterprise applications / services
using multitier architecture.
- The highly faster solutions for information management.
- JEE provides a programming development environment which improves the productivity of
development, standards for hosting / deploying enterprise applications.

J2EE Architecture is made up of three tiers, such as the client tier is used as an interactive
medium for the end user or the client & consists of web clients and application clients;

the middle tier is used for defining logical functioning units & consists of web components and
EJB components, and the enterprise data tier that is used for storage purposes in the form of
relational database & consists of containers, components, and services.

J2EE Uses Three Tiers:

Client Tier: The client tier consists of user programs that interact with the user for requests
and responses.
Middle Tier: Middle tier usually contains enterprise beans and web services that distribute
business logic for the applications.
Enterprise Data Tier: Enterprise data is stored in a relational database. This tier contains
containers, components, and services.

By : - Hemant Sir Page 1


Graphical Representation of J2EE Architecture

Usually, J2EE architecture consists of four tiers Client Tier, Web Tier, Enterprise JavaBean Tier,
and Enterprise Information Tier. The middle tier consists of the Web Tier+EJB tier.

1. Client Tier :- The client tier consists of programs or applications that interact with the user.
Usually, they are located on a different machine from the server. Client tier prompts the user
inputs into user requests, then forwarded to the J2EE server, then processed result returned
to the client. A client can be a web browser, standalone application, or server on a different
machine.
Clients can be classified as Web Clients and Application Clients.

Web Clients:- Web client consists of dynamic web pages of various mark-up languages
generated by web components running in web tier or web browser, which renders pages
received from the server. Web clients are also called thin clients that usually do not perform
things like query databases or execute business rules. Thin clients offload heavy operations to
enterprise beans that execute within the J2EE server.

By : - Hemant Sir Page 2


Applets:- Web pages received from the web tier embedded in an Applet. These run on a web
browser. Web components are APIs for creating a web client program. Web components
enable the user to design cleaner and more modular applications. They provide a way to
separate application programming.

Application Clients:- The application client runs on the client machine and handles the tasks
that give richer user interfaces. Typically the GUI is created by Swings or AWT. Application
clients can access EJBs running in the business tier using an HTTP connection.

2. Middle Tier (Web tier & EJB Tier)

components of the Middle Tier:

Web Tier /Web Component:

Web components can be servlets or JSP pages. Servlets can dynamically process the request
and generate the responses. Compared to JSP and servlets – servlets are dynamic pages to
some extent, but JSP pages are static.

The Client’s Static HTML programs and applet codes are bundled in the web tier/ Web
Component during the application assembly process. These HTML and applets are not
considered elements of web components. Server-side utility classes are bundled with web
components but are not considered web components themselves.

The web tier might include EJB components for processing user inputs and sending the input
to Enterprise Bean running in the business tier.

EJB Tier /EJB Component:


Enterprise components usually handle business code that is logic to solve particular business
domains such as banking or finance handled by enterprise bean running in the business tier.

If necessary, Enterprise Container receives data from client processes and sends it to the
enterprise information system for storage. Enterprise Bean also retrieves data from storage,
processes it, and sends it back to the client.

By : - Hemant Sir Page 3


Three kinds of beans:

Session Bean: The client uses a Session Bean for a conversation. Once the client finishes the
execution, the session bean destroys.

Entity Bean: Holds the particular data stored in a database. Once the server shuts down or the
client finishes its execution, the data of the entity bean is preserved.

Message Driven Bean: Message Bean combines the properties of Session Bean and JMS.
Which benefits the business component to receive messages asynchronously.

3. Enterprise Information System

This tier comprises database servers, enterprise resource planning systems, and other data
sources. Resources are typically located on a separate machine from the J2EE Server and
accessed by components on the business tier.

Technologies used in EIS Tier:

 Java Database Connectivity API (JDBC).


 Java Persistence API
 Java Connector Architecture.
 Java Transaction API.
Containers in J2EE Architecture

1. Application Client Container

The container includes a set of classes, libraries, and other files required to execute client
programs in their own JVM. Manages the execution of client components. It also provides
services that enable Java client programs to execute. This container is specific to the EJB
container. Compared to other containers in J2EE, this container is lightweight.

Features:

Security: Responsible for collecting authentication Data such as User Name and Password and
sending data over RMI/IIOP to the server. The server then processes the data using the JAAS
module. Even though the client container provides authentication techniques, these are not
under the control of the application client.

Naming: Allows the application clients to use Java Naming and Directory Interface (JNDI).

By : - Hemant Sir Page 4


2. Web Container

A web Container is a web server component that interacts with Java servlets. A web container
is responsible for managing the servlet lifecycle and mapping URLs.Web container handles a
request from Servlets, JSP files, and other files, including server-side code.

Web container implements a web component contract of the J2EE architecture. This provides
a runtime environment for additional web components’ security, transaction, deployment, etc.

3. EJB Container

Enterprise Java bean container consists of server components that contain business logic.
Provides local and remote access to enterprise beans. EJB container is responsible for creating
enterprise bean and binding enterprise bean to the naming services.

Installing more than one module within a single EJB container is possible. It performs
transactional actions like – Start Transaction, Commits or Rollback transactions, manages
various connection pools for database resources, and synchronizes bean instance
variables with corresponding data items stored in the database.

4. Applet Container

The container where the client’s Applet programs run may be in a web browser or other
applications that support applet programming. Applets are subject to more restrictions due to
the sandbox security model, which limits access to the client machine. Web servers download
normal web pages and execute them on the client browser.

Web Development Challenges and Solutions

#1 Web Development Process


Curating a consistent and easily maintainable web development process is one of the biggest
challenges that businesses face. Some companies are unable to follow a standard roadmap and end
up making losses. They often experiment with different approaches, which can meet their
requirements for the short term but are bound to introduce unpredictable vulnerabilities in the future.
This increases the time-to-market and makes maintenance activities more complex and time-
consuming.

Many companies focus on micromanagement rather than optimizing their development stages. They
make undefined strategies to accelerate the process but fail to notice its negative impact. This leads
to many web development problems that need regular pivoting and iteration.

By : - Hemant Sir Page 5


Solutions
 Proven Methodologies: As a business owner, you need to exploit popular software
development methodologies like Agile, Scrum, XP, etc. This will help your team work in small
sprints and complete delegated tasks within set timelines. Besides, viewing project progress in
real-time also becomes easy.
 Adopting DevOps: DevOps enhances collaboration across different teams and aspects of the
entire project life cycle, including testing and QA, development, and operations. You can take
advantage of DevOps automation services offered by top software development companies to
decrease the rate of failures for new releases, reduce the lead time between fixes, and
improve the time-to-market.
 Outsourcing IT Resources: Hire dedicated developers that are relevant to your project.
These developers have expertise and experience in planning, executing, and optimizing web
development roadmap. They have a clear idea about specific implementations and their
resulting outcomes. This can speed up your web development process, enhance collaboration,
and help you make your project live quickly.
 Standardization: Follow a standard process that focuses on consistency and continuous
improvement. This process should be easy to understand, predict, and maintain. All the
developers should work in unison to fulfill different requirements but with a solo approach.

#2 Talent Gap
Our list of web development challenges would be incomplete without mentioning the talent gap.
Having a robust web development team is really crucial for the success of your project. But
companies often find it difficult to choose the right one. Either they are skeptical about their choice or
unable to onboard the talent relevant to their business needs. This confusion leads to hiring
incompetent developers who are unable to produce quality deliverables as and when required.

Let’s say your deadline to build a real-time chat app is near, but your in-house team lacks the needed
capabilities to achieve it within a set timeframe. In such a case, you would think of hiring some more
developers. Right? But how will you identify the candidates that are a perfect fit for the project? Below
is the solution.

Solutions
 Choose Reliable Approach to Hiring: You can either hire developers from popular job
boards like LinkedIn, Indeed, Monster, etc., or choose freelancers from websites like
Freelancer, Upwork, and Fiverr. However, the most competent way is to outsource your
requirements to the right company. You can also opt for a team augmentation service model to
overcome skill deficits.
 Go for Experience-based Hiring: Choose developers with solid industry experience. Ask
them to share their portfolio and previous work samples to identify whether their experience is
relevant to your project. Check the list of clients they have served to understand their market
reputation.

By : - Hemant Sir Page 6


 Go for Skill-based Hiring: Hire developers with strong technical expertise. They should be
skilled enough to deliver solutions for different use cases. Understand their approach to
keeping up with the latest technology trends and advancements.

#3 Tech Stack
A technology stack is a series of tools that are necessary to design and develop a web application.
These tools include web-based technologies, independent applications, platforms, servers,
frameworks, APIs, IDEs, SDKs, programming languages, and more. Your chosen tech stack will
directly impact your business outcomes. It may either help your project succeed or bring it close
enough to a breakpoint.

There are various tools and technologies available that developers can use. However, this
overwhelming number of options makes it difficult for developers and business owners to pick the
right ones. Many times, they make wrong choices that later result in big technology glitches.

Solutions
 Be Clear with Your Project Requirements: Define your project requirements beforehand.
You need to have a crystal clear idea of the type of product you want to build, the target
audience and pain points to be addressed, the objective and project complexity, set timeline,
features, functionalities, and overall budget.
 Finalize Features and Functionalities: You can easily overcome such web developer
challenges by making a list of features and functionalities to add. Make sure you concentrate
on integrating the ones that will add value to your application and then finalize the right tech
stacks.
 Tech Stack Structure: You should have a good understanding of the structure of your tech
stack, which consists of two significant parts known as client-side and server-side (frontend
and backend). This will help you choose the tools wisely.
 Emerging Technologies: You need to know the importance of the popular technologies in
use and how they can uplift your project outcomes. You should always keep an eye out for
updates, new releases, and modifications for the same.

#4 Browser and Platform Compatibility


It is one of the key web application development issues that are tough to address. But ensuring that
your application is up and running on all the preferred browsers, platforms, and multiple screen sizes
is a must. These issues become more complex as legacy browsers cannot offer the needed support
for modern layouts, features, and security measures. Besides, making an app that is compatible with
various OSs and devices is not easy.

Solutions
 Testing: Perform proper testing (manual and automated) for your web app. Define a doctype,
use a CSS reset, verify support for CSS properties, focus on fallback solutions, and exploit

By : - Hemant Sir Page 7


cloud-based browser testing to ensure cross-browser compatibility. Develop the habit of using
simulators or real devices to analyze the performance under platform-specific situations.
 Coding: Validate your code and avoid writing browser-specific native code. Use platform-
agnostic tools that facilitate code reusability. Utilize frameworks and libraries such as Flutter,
React Native, Xamarin, Ionic, etc., to build cross-platform or hybrid applications. You can
follow these best practices to ensure that your code is compatible with modern platforms and
devices.

#5 UI/UX
Delivering engaging user experiences is not an easy job. It is one of the top web design
challenges developers have been facing for years now. It is all about improving interactivity and
providing simple yet effective interfaces that create a long-lasting relationship with your target
audience. It is imperative to prioritize a visual appeal that connects with your user base in a hassle-
free way. The goal is to make the app easily accessible and usable.

From integrating the things that appear on screens of your web app to everything that the end-users
click, developers need to make sure that the designs are flexible and the UX content is readily
available at each step.

Solutions
 User Personas: You need to create user-centric designs with the help of online surveys and
guerilla research. You should have a clear understanding of different user aspects like user
touchpoints, problems faced by users, location, gender, devices used, age, interests,
preferences, etc.
 Interoperability: Developers can focus on making interactions interoperable where the
exchange of data is easy and maintainable. They should create design patterns that can
handle multiple user requests seamlessly.
 Navigation: All the built-in features and functionalities should support smooth navigation.
Developers need to ensure that the users get all the necessary information and assistance to
use the app. Full-screen navigation, card-style design, and keeping frequently-used actions at
the bottom of the screen are some imperatives to consider.
 Typography: Designs should render easy-to-read and understandable content throughout the
user journey. The style and appearance of the text should follow a certain hierarchy driven by
color scheme, layout, grid, spacing, and line lengths.
 A/B Testing: Developers can build alternate designs and patterns to compare and conclude
which ones can prove beneficial. They can use popular frameworks like Angular and React
that offer an array of ready-to-use material components to develop parallel UIs.

By : - Hemant Sir Page 8


#6 Performance and Speed
These are significant challenges in web application design and development that businesses face. No
user likes delayed processes, slow-loading apps, or other lagging issues. But it is difficult to offer
consistent and stable performance throughout the entire app interaction. Additionally, keeping a
check on this performance is full of complexities.

Regularly occurring speed and performance issues can negatively affect your search engine
rankings. It may lead to poor user experiences that can lead to low conversion and impact user
retention.

Solutions
 Web App Metrics: Ensure that you track essential KPIs and user metrics such as app
installs/uninstalls, growth rate, mobile downloads, app crashes, upgrades, Lifetime Value
(LTV), and cohort analysis to improve performance.
 Tools: Leverage app analytics tools and technologies like Google Analytics, App Store
Connect, Flurry, Mix Panel, Localytics, Firebase, UXCam, Adjust, etc., to track the above
metrics and improve performance and speed.
 Google Core Web Vitals: You need to strongly follow Google’s Web Vitals. Focus on metrics
like Your Largest Contentful Paint (LCP), First Input Delay (FID), and the Cumulative Layout
Shift (CLS) of your pages.
 Optimization: You need to reduce app size and use Content Delivery Network (CDN). You
should avoid using third-party sources and focus on using the Application Performance
Monitoring (APM) System. Besides, optimizing images, code, and other content is also
necessary.

#7 Scalability
When it comes to web development, scalability is of utmost importance. It helps exploit the web
assets to expand or contract the system capacity. It helps businesses to interact with users while
simultaneously acquiring new ones. That’s why many companies strategize to use their bandwidth
and systems properly. However, this decision cannot help them in achieving the desired scalability.

Because scalability is not about the system performance or its bandwidth; instead, it stands among
the web development challenges that require balancing the load on the server. So, when the traffic
increases, you need to add more servers to maintain the balance. This means that your app should
have the ability to cater to the requirements of many users at the same time.

Solutions
 Cloud Computing: Your company should utilize cloud computing (Vertical and Horizontal
scaling) capabilities. It can explore popular cloud platforms and solutions such as Amazon
Web Services (AWS), Google Cloud Platform, Microsoft Azure, DigitalOcean, IBM Cloud, etc.,
to manage increasing load effortlessly.

By : - Hemant Sir Page 9


 Microservices and other Distributed Systems Architectures: When conventional n-tier
architecture is not enough for your scalability needs, one needs to utilize distributed systems
such as Microservices, distributed caching solutions, and sharded databases architecture.
These technologies should help you to scale to hundreds of millions of users.

#8 Security
Managing security is among the considerable software development challenges driven by the
increasing number of cyberattacks. These cyberattacks are security misconfiguration, cross-site
scripting, broken authentication & access control, injection, XML external entities, and more.
Companies find it difficult to address these attacks that later lead to data malfunction, poor user
authorization, phishing, and other app vulnerabilities.

If your application deals with critical user information like payment details, contact, or confidential
documents, then these issues can cause more harm than you can ever imagine. That’s why it is
necessary to closely monitor your app security and make it a continuous process.

Solutions
 SSL Certificates: To ensure secure, confidential information exchange between clients and
servers, you need to back up your web app with SSL certificates (HTTP over SSL). This way,
both the server and the client encrypt data before transmitting, then decrypt it upon receipt.
 Hosting: You need to choose a secure web host. This host should provide Secure File
Transfer Protocol (SFTP), file backup to a remote server, and regular security upgrades
alongside using Rootkit Scanner.
 Validation: You need to validate user input and ensure it falls within the expected characters.
You can easily sanitize and eliminate unwanted characters by escaping, replacing, removing,
or encoding characters.
 Authentication: Your company should follow a good password policy. Along with biometrics
as well as certificates and token-based policy, it should opt for two-factor and multi-factor
authentication.
 Accessibility: When it comes to accessibility, always follow the Principle of Least Privilege
(PoLP). To put it simply, give access to only the necessary data, tools, and resources to avoid
any security breach or misconfiguration.
Some other ways to consider are exceptions and container management, using the secrets
mechanism in Docker or Kubernetes, testing (static, dynamic, and penetration), and Extended
Detection and Response (XDR) solutions.

#9 Third-party Integrations
Third-party integrations are not limited to payment gateways. Several functionalities can be added to
your application through these integrations. For instance, you need Google Maps API integration to
access maps from your app. Third-party integrations can also help you enhance social media
capabilities and implement dedicated multi-language support. What makes them one of the most

By : - Hemant Sir Page 10


important web application development challenges to overcome is their secure integrations with app
customizations.

In the case of outdated APIs, they become an immediate threat that acts as a loophole to unforeseen
issues. Moreover, there are a few technical differences between web apps and third-party services,
which can be easily resolved with customized APIs. But if your app is based on a monolithic
architecture, this process becomes too complex.

Solutions

The best solution to address this challenge is to ensure that the changes made by third-party service
providers reflect in your app architecture. You should employ QA teams to monitor these services and
gain all the required information about the changes in the architecture or the API code.

To achieve secure integrations and uninterrupted performance, you need to make sure that your app
architecture is in sync with your API code. Here, maintenance of the code and regular updates can
uplift the production alongside reducing the cost of development.

#10 Support and Maintenance


The real technical challenges in software development begin just after your web app is live. Yes, we
are talking about post-launch support and maintenance activities. Poor execution of these activities
can lead to several issues like unresponsive web pages, performance issues, slow loading, etc. You
will face other problems if you want to update the legacy APIs or upgrade the entire application for
security purposes. During such maintenance activities, ensuring zero downtime becomes even more
difficult. There are various dependencies that can lead to downtime.

Solutions
 Monitoring: If you want to support your maintenance activities, monitoring your app is a must.
You need to closely observe the essential aspects of your app to plan effective remediation.
This will help you predict turbulent circumstances and plan immediate bug fixes as and when
required.
 Microservices: You need to have a web architecture with minimal dependencies in place to
experience higher uptime while updating your app. And microservices architecture can help
you do that. It is a comprehensive suite of services that upgrades without causing any harm to
your existing system. This means that no function is disturbed or affected during the upgrade.
 Future-proofing: Create applications that can meet your existing and upcoming requirements
with ease. You need to concentrate on making an app that can support more users than
expected. It should easily switch servers and databases. It should also have the flexibility to
accept new features and functionalities.

By : - Hemant Sir Page 11


Life Cycle of a Servlet (Servlet Life Cycle)

1. Life Cycle of a Servlet


2. Servlet class is loaded
3. Servlet instance is created
4. init method is invoked
5. service method is invoked
6. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The
servlet is in new state if servlet instance is created. After invoking the init() method, Servlet
comes in the ready state. In the ready state, servlet performs all the tasks. When the web
container invokes the destroy() method, it shifts to the end state.

By : - Hemant Sir Page 12


1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The servlet instance
is created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The init method is used to
initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is
given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is received. If
servlet is not initialized, it follows the first three steps as described above then calls the service
method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once.
The syntax of the service method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from the service. It
gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax
of the destroy method of the Servlet interface is given below:

public void destroy()

Steps to create a servlet example


1. Steps to create the servlet using Tomcat server
1. Create a directory structure
2. Create a Servlet

By : - Hemant Sir Page 13


3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the application

There are given 6 steps to create a servlet example. These steps are required for all the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

1)Create a directory structures


The directory structure defines that where to put the different types of files so that web container
may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see the
directory structure that must be followed to create the servlet.

As you can see that the servlet class file must be in the classes folder. The web.xml file must be under the
WEB-INF folder.

2)Create a Servlet

By : - Hemant Sir Page 14


There are three ways to create the servlet.

1. By implementing the Servlet interface


2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests
such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are
inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get request
is the default request.

DemoServlet.java

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data

//writing html in the stream


pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");

pw.close();//closing the stream


}}

By : - Hemant Sir Page 15


3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:

Jar file Server


1) servlet-api.jar Apache Tomcat
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss

Two ways to load the jar file

 set classpath
 paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet
in WEB-INF/classes directory.

4)Create the deployment descriptor (web.xml file)


The deployment descriptor is an xml file, from which Web Container gets the information about the
servet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There are
many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run
the simple servlet program.
web.xml file

<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

By : - Hemant Sir Page 16


Description of the elements of web.xml file
There are too many elements in the web.xml file. Here is the illustration of some elements that is used
in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.


<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side
to invoke the servlet.

5)Start the Server and deploy the project


To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.

Unit – 5 Spring
Spring Framework
Spring is a lightweight framework. It can be thought of as a framework of frameworks because it
provides support to various frameworks such as Struts, Hibernate, Tapestry, EJB, JSF, etc. The
framework, in broader sense, can be defined as a structure where we find solution of the various
technical problems.

The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM, WEB MVC
etc. We will learn these modules in next page. Let's understand the IOC and Dependency Injection
first.

Advantages of Spring Framework


There are many advantages of Spring Framework. They are as follows:

1) Predefined Templates

Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need
to write too much code. It hides the basic steps of these technologies.

By : - Hemant Sir Page 17


Let's take the example of JdbcTemplate, you don't need to write the code for exception handling,
creating connection, creating statement, committing transaction, closing connection etc. You need to
write the code of executing query only. Thus, it save a lot of JDBC code.

2) Loose Coupling

The Spring applications are loosely coupled because of dependency injection.

3) Easy to test

The Dependency Injection makes easier to test the application. The EJB or Struts application require
server to run the application but Spring framework doesn't require server.

4) Lightweight

Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't
force the programmer to inherit any class or implement any interface. That is why it is said non-
invasive.

5) Fast Development

The Dependency Injection feature of Spring Framework and it support to various frameworks makes
the easy development of JavaEE application.

6) Powerful abstraction

It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.

7) Declarative support

It provides declarative support for caching, validation, transactions and formatting.

Inversion Of Control (IOC) and Dependency Injection


These are the design patterns that are used to remove dependency from the programming code.
They make the code easier to test and maintain. Let's understand this with the following code:

class Employee{
Address address;
Employee(){
address=new Address();
}
}
By : - Hemant Sir Page 18
In such case, there is dependency between the Employee and Address (tight coupling). In the
Inversion of Control scenario, we do this something like this:

class Employee{

Address address;

Employee(Address address){

this.address=address;

Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code if our
logic is moved to new environment.

In Spring framework, IOC container is responsible to inject the dependency. We provide metadata to
the IOC container either by XML file or annotation.

Advantage of Dependency Injection

o makes the code loosely coupled so easy to maintain


o makes the code easy to test
o

Spring AOP (Aspect Oriented Programming)


Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also provides
modularity. But the key unit of modularity is aspect than class.

AOP breaks the program logic into distinct parts (called concerns). It is used to increase
modularity by cross-cutting concerns.

A cross-cutting concern is a concern that can affect the whole application and should be
centralized in one location in code as possible, such as transaction management,
authentication, logging, security etc.

By : - Hemant Sir Page 19


AOP Concepts and Terminology
o Join point
o Advice
o Pointcut
o Introduction
o Target Object
o Aspect
o Interceptor
o AOP Proxy
o Weaving

Join point

Join point is any point in your program such as method execution, exception handling, field access
etc. Spring supports only method execution join point.

Advice

Advice represents an action taken by an aspect at a particular join point. There are different types of
advices:

o Before Advice: it executes before a join point.


o After Returning Advice: it executes after a joint point completes normally.
o After Throwing Advice: it executes if method exits by throwing an exception.
o After (finally) Advice: it executes after a join point regardless of join point exit whether
normally or exceptional return.
o Around Advice: It executes before and after a join point.

Pointcut

It is an expression language of AOP that matches join points.

By : - Hemant Sir Page 20


Introduction

It means introduction of additional method and fields for a type. It allows you to introduce new
interface to any advised object.

Target Object

It is the object i.e. being advised by one or more aspects. It is also known as proxied object in spring
because Spring AOP is implemented using runtime proxies.

Aspect

It is a class that contains advices, joinpoints etc.

Interceptor

It is an aspect that contains only one advice.

AOP Proxy

It is used to implement aspect contracts, created by AOP framework. It will be a JDK dynamic proxy or
CGLIB proxy in spring framework.

Weaving

It is the process of linking aspect with other application types or objects to create an advised object.
Weaving can be done at compile time, load time or runtime. Spring AOP performs weaving at
runtime.

By : - Hemant Sir Page 21


Spring MVC Architecture
A Spring MVC is a Java framework which is used to build web applications. It follows the Model-View-
Controller design pattern. It implements all the basic features of a core spring framework like
Inversion of Control, Dependency Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the help
of DispatcherServlet. Here, DispatcherServlet is a class that receives the incoming request and maps
it to the right resource such as controllers, models, and views.

Spring Web Model-View-Controller

o Model - A model contains the data of the application. A data can be a single object or a
collection of objects.
o Controller - A controller contains the business logic of an application. Here, the @Controller
annotation is used to mark the class as the controller.
o View - A view represents the provided information in a particular format. Generally, JSP+JSTL is
used to create a view page. Although spring also supports other view technologies such as
Apache Velocity, Thymeleaf and FreeMarker.
o Front Controller - In Spring Web MVC, the DispatcherServlet class works as the front
controller. It is responsible to manage the flow of the Spring MVC application.

By : - Hemant Sir Page 22


Understanding the flow of Spring Web MVC

o As displayed in the figure, all the incoming request is intercepted by the DispatcherServlet that
works as the front controller.
o The DispatcherServlet gets an entry of handler mapping from the XML file and forwards the
request to the controller.
o The controller returns an object of ModelAndView.
o The DispatcherServlet checks the entry of view resolver in the XML file and invokes the
specified view component.

Advantages of Spring MVC Framework


Let's see some of the advantages of Spring MVC Framework:-

o Separate roles - The Spring MVC separates each role, where the model object, controller,
command object, view resolver, DispatcherServlet, validator, etc. can be fulfilled by a
specialized object.
o Light-weight - It uses light-weight servlet container to develop and deploy your application.
o Powerful Configuration - It provides a robust configuration for both framework and
application classes that includes easy referencing across contexts, such as from web controllers
to business objects and validators.
o Rapid development - The Spring MVC facilitates fast and parallel development.

By : - Hemant Sir Page 23


o Reusable business code - Instead of creating new objects, it allows us to use the existing
business objects.
o Easy to test - In Spring, generally we create JavaBeans classes that enable you to inject test
data using the setter methods.
o Flexible Mapping - It provides the specific annotations that easily redirect the page.

Bean Factory vs Application Context


Bean Factory Hierarchy
 public interface BeanFactory
 public interface ListableBeanFactory extends BeanFactory
 public interface ConfigurableListableBeanFactory extends ListableBeanFactory,
AutowireCapableBeanFactory, ConfigurableBeanFactory
 public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable
 public class XmlBeanFactory extends DefaultListableBeanFactory
 Ex – BeanFactory factory = new XmlBeanFactory(new ClassPathResource(“beans.xml”));
Application Context Hierarchy
 public interface ApplicationContext extends ListableBeanFactory,
HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher,
ResourcePatternResolver
 public interface ConfigurableApplicationContext extends ApplicationContext
 public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext
 public abstract class AbstractRefreshableApplicationContext extends
AbstractApplicationContext
 public abstract class AbstractRefreshableConfigApplicationContext extends
AbstractRefreshableApplicationContext
 public abstract class AbstractXmlApplicationContext extends
AbstractRefreshableConfigApplicationContext
 public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext
 Ex – ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”);

REPORT THIS AD

By : - Hemant Sir Page 24


Bean Factory
 Bean instantiation/wiring.
 It exists for backward compatibility.
 Manual BeanPostProcessor registration
 Support Lazy loading – It instantiates bean when you call getBean() method.
 It is OK for testing and non-production use.
Application Context
 Bean instantiation/wiring.
 Automatic BeanPostProcessor registration.
 Automatic BeanFactoryPostProcessor registration.
 Convenient MessageSource access (for i18n).
 ApplicationEvent publication – can publish events to beans that are registered as
listeners.
 Support Annotation-based dependency Injection. -@Autowired, @PreDestroy
 Support many enterprise services such JNDI access, EJB integration, remoting.
 Support Aggressive loading – It instantiates Singleton bean when the container is
started, It doesn’t wait for getBean() to be called.

By : - Hemant Sir Page 25


By : - Hemant Sir Page 26
Now server is started successfully.

2) How to change port number of apache tomcat

Changing the port number is required if there is another server running on the same system with
same port number.Suppose you have installed oracle, you need to change the port number of apache
tomcat because both have the default port number 8080.

By : - Hemant Sir Page 27


Open server.xml file in notepad. It is located inside the apache-tomcat/conf directory . Change the
Connector port = 8080 and replace 8080 by any four digit number instead of 8080. Let us replace it
by 9999 and save this file.

5) How to deploy the servlet project


Copy the project and paste it in the webapps folder under apache tomcat.

But there are several ways to deploy the project. They are as follows:

o By copying the context(project) folder into the webapps directory


o By copying the war folder into the webapps directory
o By selecting the folder path from the server
o By selecting the war file from the server

Here, we are using the first approach.

You can also create war file, and paste it inside the webapps directory. To do so, you need to use jar
tool to create the war file. Go inside the project directory (before the WEB-INF), then write:

1. projectfolder> jar cvf myproject.war *

Creating war file has an advantage that moving the project from one location to another takes less
time.

6) How to access the servlet


Open broser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:

1. http://localhost:9999/demo/welcome

By : - Hemant Sir Page 28

You might also like