WT_Module_V JSF

You might also like

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

MODULE-V

Java Spring Framework (JSF)

Introduction to Java Spring Framework


Spring Framework is a Java platform that provides comprehensive
infrastructure support for developing Java applications. Spring handles the
infrastructure so you can focus on your application.
Spring enables you to build applications from “plain old Java objects”
(POJOs) and to apply enterprise services non-invasively to POJOs. This
capability applies to the Java SE programming model and to full and partial
Java EE.

The Java Spring Framework (JSF) is an open-source application


framework that provides infrastructure support for developing Java
applications.

Spring is a lightweight framework.

One of the most popular Java Enterprise Edition (Java EE) frameworks,
Spring helps developers create high performing applications.

Spring framework makes the easy development of Java EE application.

It is helpful for beginners and experienced persons.

It can be thought of as a framework of frameworks because it provides


support to various frameworks such as Struts, Hibernate and EJB.
(Enterprise Java Beans)

Advantages of Java Spring Framework

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

1) Predefined Templates

Spring framework provides templates for JDBC, Hibernate, EJB etc.


technologies. So there is no need to write too much code. It hides the basic
steps of these technologies.

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 The Spring Framework doesn't force the


programmer to inherit any class or implement any interface.

5) Fast Development

The Dependency Injection feature of Spring Framework and it support to


various frameworks makes the easy development of Java EE application.

6) Powerful Abstraction

It provides powerful abstraction to Java EE specifications such


as JMS, JDBC, ect.,

7) Declarative Support

It provides declarative support for caching, validation, transactions and


formatting.

Disadvantages / Drawbacks of Java Spring Frameworks

• Fewer guidelines: There are no proper procedures in Spring


documentation
• Complexity: It is pretty complex to work with Spring. Developers
must have more relevant skills and expertise to use this framework.
• Hard to learn: If you have no experience regarding development, it
is quite difficult for you to learn Spring. It is due to the incorporation
of the latest programming techniques in this framework.
• Uses XML: We need lots of XML while developing a Spring app.
It can also be problematic for developers.
• Parallel mechanism: Developers can get multiple options. It can be
helpful for developers but can also be a point of confusion.
Developers can face problems in selecting the right mechanism and
it results in making wrong decisions. These mistaken choices might
cause major delays in developing the apps.

Architecture of Spring or Java Spring Framework Modules

The Java Spring Framework comprises of many modules such as core,


beans, context, expression language, AOP, Aspects, Instrumentation,
JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, Struts etc. These
modules are grouped into Test, Core Container, AOP, Aspects,
Instrumentation, Data Access / Integration, Web (MVC / Remoting) as
displayed in the following diagram.

aspect-oriented programming
object-relational mapping
Java Messaging Service
Object xml Model
develop MVC (Model View Controller) based web
applications.
1. struts2 = webwork + struts1
POJO (Plain Old Java Objects)
Core Container
The Core Container consists of the Core, Beans, Context, and Expression
Language modules.
The Core and Beans modules provide the fundamental parts of the
framework, including the IoC and Dependency Injection features.
The BeanFactory is a sophisticated implementation of the factory pattern.
It removes the need for programmatic singletons and allows you to
decouple the configuration and specification of dependencies from your
actual program logic.
The Context module builds on the solid base provided by the Core and
Beans modules: it is a means to access objects in a framework-style manner
that is similar to a JNDI registry. The Context module inherits its features
from the Beans module and adds support for internationalization (using,
for example, resource bundles), event-propagation, resource-loading, and
the transparent creation of contexts by, for example, a servlet container.
The Context module also supports Java EE features such as EJB, JMX ,and
basic remoting. The ApplicationContext interface is the focal point of the
Context module.
The Expression Language module provides a powerful expression
language for querying and manipulating an object graph at runtime. It is an
extension of the unified expression language (unified EL) as specified in
the JSP 2.1 specification. The language supports setting and getting
property values, property assignment, method invocation, accessing the
context of arrays, collections and indexers, logical and arithmetic operators,
named variables, and retrieval of objects by name from Spring's IoC
container. It also supports list projection and selection as well as common
list aggregations.
Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM,
JMS and Transaction modules.
The JDBC module provides a JDBC-abstraction layer that removes the
need to do tedious JDBC coding and parsing of database-vendor specific
error codes.
The ORM module provides integration layers for popular object-relational
mapping APIs, including JPA, JDO, Hibernate, and iBatis. Using the
ORM package you can use all of these O/R-mapping frameworks in
combination with all of the other features Spring offers, such as the simple
declarative transaction management feature mentioned previously.
The OXM module provides an abstraction layer that supports Object/XML
mapping implementations for JAXB, Castor, XMLBeans, JiBX and
XStream.
The Java Messaging Service (JMS) module contains features for producing
and consuming messages.
The Transaction module supports programmatic and declarative
transaction management for classes that implement special interfaces and
for all your POJOs (plain old Java objects).
Web
The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-
Portlet modules.
Spring's Web module provides basic web-oriented integration features
such as multipart file-upload functionality and the initialization of the IoC
container using servlet listeners and a web-oriented application context. It
also contains the web-related parts of Spring's remoting support.
The Web-Servlet module contains Spring's model-view-controller (MVC)
implementation for web applications. Spring's MVC framework provides
a clean separation between domain model code and web forms, and
integrates with all the other features of the Spring Framework.
The Web-Struts module contains the support classes for integrating a
classic Struts web tier within a Spring application. Note that this support is
now deprecated as of Spring 3.0. Consider migrating your application to
Struts 2.0 and its Spring integration or to a Spring MVC solution.
The Web-Portlet module provides the MVC implementation to be used in
a portlet environment and mirrors the functionality of Web-Servlet module.
AOP and Instrumentation
Spring's AOP module provides an AOP Alliance-compliant aspect-
oriented programming implementation allowing you to define, for example,
method-interceptors and pointcuts to cleanly decouple code that
implements functionality that should be separated. Using source-level
metadata functionality, you can also incorporate behavioral information
into your code, in a manner similar to that of .NET attributes.
The separate Aspects module provides integration with AspectJ.
The Instrumentation module provides class instrumentation support and
classloader implementations to be used in certain application servers.
Test
The Test module supports the testing of Spring components with JUnit or
TestNG. It provides consistent loading of Spring ApplicationContexts and
caching of those contexts. It also provides mock objects that you can use
to test your code in isolation.
Dependency Injection in Spring

⚫ Dependency Injection (DI) is a design pattern that removes the


dependency from the programming code.

⚫ It is can be easy to manage and test the application.

⚫ Dependency Injection makes our programming code loosely coupled.

Example :
class Employee{
Address address;
Employee(Address address)
{
this.address=address;
}
public void setAddress(Address address)
{
this.address=address;
}
}

Types of Dependency Injection in Spring Framework

Spring framework provides two ways to inject dependency

A) By constructor method
B) By setter method

A) . Dependency Injection by Constructor Method

The Inject the dependency by constructor. The <constructor-


arg> subelement of <bean> is used for constructor injection. The following
to use inject are

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Example of Dependency Injection by Constructor Method

public class Employee {


private int id;
private String name;
public Employee()
{
System.out.println("def cons");
}
public Employee(int id) {
this.id = id;
}
public Employee(String name)
{
this.name = name;
}
public Employee(int id, String name)
{
this.id = id;
this.name = name;
}
void show()
{
System.out.println(id+" "+name);
}
}
B) . Dependency Injection by setter method

The inject the dependency by setter method also.


The <property> subelement of <bean> is used for setter injection. The
following to use inject are

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Example of Dependency Injection by setter method

public class Employee {


private int id;
private String name;
private String city;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
void display()
{
System.out.println(id+" "+name+" "+city);
}
}

Inversion of a Control (IOC) Containers in java Objects

The IoC container is responsible to instantiate, configure and assemble


the objects. The IoC container gets information from the XML file and
works accordingly. The main tasks performed by IoC container are:

⚫ To instantiate the application class


⚫ To configure the object
⚫ To assemble the dependencies between the objects

There are two types of IoC containers. They are:

1. BeanFactory
2. ApplicationContext

1. BeanFactory

The XmlBeanFactory is the implementation class for the BeanFactory


interface. To use the BeanFactory, to create the instance of
XmlBeanFactory class as given below:

Example :

Resource resource=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(resource);
2. ApplicationContext

The ClassPathXmlApplicationContext class is the implementation class of


ApplicationContext interface. We need to instantiate the
ClassPathXmlApplicationContext class to use the ApplicationContext as
given below:

Example:

ApplicationContext context = new ClassPathXmlApplicationContext("Ap


plicationContext.xml");

Autowiring in Spring Framework

⚫ Autowiring feature of spring framework enables you to inject the object


dependency implicitly.
⚫ It internally uses setter or constructor injection.
⚫ Autowiring can't be used to inject primitive and string values.
⚫ It works with reference only.

Advantage of Autowiring

⚫ It requires the less code because we don't need to write the code to
inject the dependency explicitly.

Disadvantage of Autowiring

⚫ No control of programmer.
⚫ It can't be used for primitive and string values.

Example of Autowiring

<bean id="a" class="org.sssit.A" autowire="byName"></bean>

Autowiring Modes in Spring Framework


There are many autowiring modes using in spring framework:

N Mode Description
o.

1) No It is the default autowiring mode. It means no autowiring by default.

2) byName The byName mode injects the object dependency according to name of the bean.
In such case, property name and bean name must be same. It internally calls setter
method.

3) byType The byType mode injects the object dependency according to type.
So property name and bean name can be different. It internally calls setter method.

4) constructor The constructor mode injects the dependency by calling the constructor of
the class. It calls the constructor having large number of parameters.

5) autodetect It is deprecated since Spring ver 3.

Introduction to Spring JDBC

Spring Jdbc is a powerful mechanism to connect to the database and


execute SQL queries. It internally uses JDBC API, but eliminates a lot of
problems of JDBC API.

Advantage of Spring Jdbc

Spring Jdbc eliminates all the above mentioned problems of JDBC API.

It provides you methods to write the queries directly, so it saves a lot of


work and time.

Drawbacks or Dis advantages of JDBCAPI

⚫ We need to write a lot of code before and after executing the query,
such as creating connection, statement, closing resultset, connection etc.
⚫ We need to perform exception handling code on the database logic.
⚫ We need to handle transaction.
⚫ Repetition of all these codes from one to another database logic is a
time consuming task.
Step1: Create Employee table in MySQL
create table employee(
id number(10),
name varchar2(50),
salary number(10)
);
Step2 : Create Employee.java file
import java.io.*;
Import java.sql.*;
public class Employee
{
private int id;
private String name;
private float salary;
//no-arg and parameterized constructors
//getters and setters
}
Step 3|: Create spring framework using EmployeeDao.java file

import java.io.*;
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;

public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {


this.jdbcTemplate = jdbcTemplate;
}
public Boolean saveEmployeeByPreparedStatement(final Employee e){
String query="insert into employee values(?,?,?)";
return jdbcTemplate.execute(query,new PreparedStatementCallback<Boole
an>(){
public Boolean doInPreparedStatement(PreparedStatement ps)
throws SQLException, DataAccessException {
ps.setInt(1,e.getId());
ps.setString(2,e.getName());
ps.setFloat(3,e.getSalary());
return ps.execute();
}
});
}
}

Step 4: Create a web.xml file

<?xml version="1.0" encoding="UTF-8"?>


<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds" class="org.springframework.jdbc.datasource.DriverManager
DataSource">
<property name="driverClassName" value="mysql.jdbc.driver.MySqlDriver
" />
<property name="url" value="jdbc:mysql:thin:@localhost:8080:xe" />
<property name="username" value="system" />
<property name="password" value="oracle" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTempl
ate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.mrec.EmployeeDao">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>

Step 5 : Execute the Test.java file.


import org.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationCo
ntext;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicati
onContext.xml");
EmployeeDao dao=(EmployeeDao)ctx.getBean("edao");
dao.saveEmployeeByPreparedStatement(new Employee(108,"Amit",35000));
}
}
Introduction to Hibernate Framework

⚫ Hibernate is a Java framework that simplifies the development of Java


application to interact with the database.
⚫ It is an open source, lightweight, ORM (Object Relational Mapping)
tool.
⚫ Hibernate implements the specifications of JPA (Java Persistence API)
for data persistence.

ORM Tool :

⚫ An ORM tool simplifies the data creation, data manipulation and data
access.
⚫ It is a programming technique that maps the object to the data stored in
the database.
⚫ The ORM tool internally uses the JDBC API to interact with the
database.

What is JPA?

⚫ Java Persistence API (JPA) is a Java specification that provides certain


functionality and standard to ORM tools.
⚫ The javax.persistence package contains the JPA classes and interfaces.

Hibernate Architecture

The Hibernate Architecture is the many objects such as persistent object,


session factory, transaction factory, connection factory, session,
transaction etc.

The Hibernate architecture is categorized in four layers.


⚫ Java Application Layer
⚫ Hibernate Framework Layer
⚫ Backhand API Layer
⚫ Database Layer

Hibernate Framework Structure


Advantages of Hibernate Framework

Following are the advantages of hibernate framework:

1) Open Source and Lightweight

Hibernate framework is open source under the LGPL license and


lightweight.

2) Fast Performance

The performance of hibernate framework is fast because cache is internally


used in hibernate framework. There are two types of cache in hibernate
framework first level cache and second level cache. First level cache is
enabled by default.

3) Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of SQL.


It generates the database independent queries. So you don't need to write
database specific queries. Before Hibernate, if database is changed for the
project, we need to change the SQL query as well that leads to the
maintenance problem.

4) Automatic Table Creation

Hibernate framework provides the facility to create the tables of the


database automatically. So there is no need to create tables in the database
manually.

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status

Hibernate supports Query cache and provide statistics about query and
database status.
Draw backs of Hibernate Framework

The hibernate generates lots of SQL statements at runtime so it is slower


than pure JDBC.

1. The Hibernate is not much flexible in case of composite mapping.


2. It is not understanding of composite mapping is complex.
3. Hibernate does not support some type of queries which are
supported by JDBC.
4. Boilerplate code issue, actually we need to write same code in
several files in the same application, but spring eliminated this.
5. Not good for small project.

Spring MVC Arecheture


⚫ 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.
⚫ The DispatcherServlet is a class that receives the incoming request
and maps it to the right resource such as controllers, models, and views.

⚫ Model : A model contains the data of the application. A data can be a


single object or a collection of objects.
⚫ Controller: A controller contains the business logic of an application.
Here, the @Controller annotation is used to mark the class as the
controller.
⚫ View : A view represents the provided information in a particular
format. Generally, JSP+JSTL is used to create a view page.
⚫ 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.

Advantages of Spring MVC Framework

⚫ 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.
⚫ Light-weight : It uses light-weight servlet container to develop and
deploy your application.
⚫ 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.
⚫ Rapid development : The Spring MVC facilitates fast and parallel
development.
⚫ Reusable business code: Instead of creating new objects, it allows us
to use the existing business objects.
⚫ Easy to test : In Spring, generally we create Java Beans classes that
enable you to inject test data using the setter methods.
⚫ Flexible Mapping : It provides the specific annotations that easily
redirect the page.

Disadvantage or Draw backs of Spring MVC Architecture

⚫ Complexity: Working with Spring is more complex. It requires a lot


of expertise. If you have not used Spring before, first you will have to
learn. The learning curve is also difficult, so if you have not a lot of
development experience, it is difficult to learn.
⚫ Parallel Mechanism: It provides multiple options to developers.
These options create confusion to developers that which feature to use
and which to not and wrong decisions may lead to significant delays.
⚫ No Specific Guidelines: It does not care about XSS or cross-site
scripting. With this in mind, we need to figure out ways on how to stop
hackers from infiltrating your application yourself.
⚫ High Learning Curve: If you have not development experience in the
field, it would be quite difficult to learn It is difficult due to new
programming methods.
⚫ Lots of XML: Developing a Spring application requires lots of XML.

You might also like