Anda di halaman 1dari 61

J2EE

Frameworks
- Hibernate -
ORM framework
(Object to
relational
mapping) DB
- Spring - ORM,
Service level
architecture,
MVC, DI
- Struts - MVC

JDBC

POJO class (Plain


Old Java Object /
Java Bean class)
Rules:
- Class must be
public
- all fields of this
class should be
“private”
- Class must
have public default
constructor
- For all fields
you should have
getter( ) and
setter( ) methods.

example of POJO
class
package
com.pga;
public class Student
{
private int id;
private String
name;
private float
marks;

public Student()
{}
public int getId(
) { return this.id; }
public void
setId(int id) { this.id =
id; }

public String
getName( ) { return
this.name; }
public void
setName(String name)
{ this.name = name; }

public float
getMarks( ) { return
this.marks; }
public void
setMarks(String marks)
{ this.marks = marks; }
}

- Create POJO class


(Student.java) - Per
table
- Create Mapping
file in XML
(student.hbm.xml) - Per
table
- Hibernate
configuration file
(hibernate.cfg.xml) -
One per project

Hibernate Dialect
(Component of
Hibernate which will
convert object
oriented query into
SQL query with the
help of JDBC Driver)

http://hibernate.o
rg/orm/download
s/

Hibernate-
folder/project/hib
ernate-
ehcache/src/test/
resouces/hiberna
te-
config/domain/Ev
ent.hbm.xml
/
protject/documen
tation/src/main/d
ocbook/integrati
onGuide/en-
us/extras/hiberna
te.cfg.xml

HCQL -
Hibernate
Criteria Query
Language

Hibernate
application using
annotation :
- Instead of defining
mapping in XML file,
Hibernate provides
some
annotations(@Entity,@T
able,@Id,@Column) to
write same mapping in
POJO class.

- In configuration
file, add mapping as
below:
<mapping
class="com.pga.Student"
/>

Dept <—> Emp

Dept -> Emp (1 to M)


Emp -> Dept (M to 1)
Changes at class Level:
- In Dept class Set of
Emp object is added
- In Emp class Dept
object is added

Mapping file changes:


- in dept mapping file
<set name="emps"
table="emp">
<key>
<column
name="deptId" />
</key>
<one-to-many
class="Emp" />
</set>
- In Emp mapping file
<many-to-one
name="dept" class="Dept"
fetch="select">
<column
name="deptId" />
</many-to-one>

Entry for MtoM relation in Movie


mapping file is:
<set name="actors"
table="movie_actor">
<key>
<column
name="mid"/>
</key>
<many-to-many entity-
name="com.pga.Actor">
<column
name="aid"/>
</many-to-many>
</set>
Entry for MtoM relation in Actor
mapping file is:
<set name="movies"
table="movie_actor">
<key>
<column
name="aid"/>
</key>
<many-to-many entity-
name="com.pga.Movie">
<column
name="mid"/>
</many-to-many>
</set>
Build tool
Maven, ant, gradle

Maven - Use for building


the project with some
dependencies.

-
https://maven.apache.org/
download.cgi

Struts 2 MVC:
The model contains
the business logic and
interact with the
persistance storage to
store, retrive and
manipulate data.
The view is
responsible for
dispalying the results
back to the user. In
Struts the view layer is
implemented using JSP.
The controller
handles all the request
from the user and
selects the appropriate
action.

The following events happen when


the Client browser issues an HTTP
request.
• The ActionServlet receives the
request.
• The struts-config.xml file contains
the details regarding the Actions,
ActionForms, ActionMappings and
ActionForwards.
• During the startup the

ActionServelet reads the struts-


config.xml file and creates a
database of configuration objects.
Later while processing the
request the ActionServlet makes
decision by refering to this object.
When the ActionServlet receives the
request it does the following tasks.
• Bundles all the request values into a
JavaBean class which extends
Struts ActionForm class.
• Decides which action class to invoke

to process the request.


• Validate the data entered by the

user.
• The action class process the request

with the help of the model


component. The model interacts
with the database and process
the request.
• After completing the request
processing the Action class
returns an ActionForward to the
controller.
• Based on the ActionForward the

controller will invoke the


appropriate view.
• The HTTP response is rendered back

to the user by the view


component.

About Struts 2 Request Flow


1. The controller receives the user request and
determine which Struts 2 action to invoke.
2. The framework creates an instance of this
action and associate it with the newly
created instance of the ActionInvocation.
3. In Struts 2 the invocation of action should
pass through a series of interceptors as
defined in the application's XML file.
4. The framework calls the ActionInvocations
invoke() method to start the execution of
the action.
5. Each time the invoke() method is called,
ActionInvocation consults its state and
executes whichever interceptor comes
next.
6. ActionInvocation hands control over to the
interceptor in the stack by calling the
interceptors intercept() method.
7. The intercept() method of the interceptor
intern calls the invoke() method of the
ActionInvocation till all the interceptors
are invoked, in the end the action itself will
be called and the corresponding result will
be returned back to the user.
8. Some interceptor do work before the action
is executed and some do work after the
action is executed. It's not necessary that
it should do something each time it is
invoked.
9. These interceptors are invoke both before
and after the action.
10. First all the interceptors are executed
in the order they are defined in the
stack.
11. Then the action is invoked and the result is
generated.
12. Again all the interceptors present in the
stack are invoked in the reverse order.
13. The other important features of Struts 2
are OGNL and ValueStack.
14. Object-Graph Navigation Language
(OGNL) is a powerful expression language
that is used to reference and manipulate
data on the ValueStack.
15. OGNL help in data transfer and type
conversion.
16. OGNL expression language provides
simplified syntax to reference java objects.
17. OGNL is used to bind the java-side data
properties to the string-based view layer.

http://struts.apache.org/
download.cgi
FilterDispatcher
<filter>
<filter-
name>struts2</filter-name>
<filter-class>

org.apache.struts2.d
ispatcher.FilterDispa
tcher
</filter-class>
</filter>

<filter-mapping>
<filter-
name>struts2</filter-name>
<url-pattern>/*</url-
pattern>
</filter-mapping>

StrutsPrepareAndExe
cuteFilter
Entry of controller in
web.xml file:
<filter>
<filter-
name>struts2</filter-
name>
<filter-class>
org.apache.strut
s2.dispatcher.ng.
filter.StrutsPrepa
reAndExecuteFilt
er
</filter-class>
</filter>

<filter-mapping>
<filter-
name>struts2</filter-
name>
<url-
pattern>/*</url-
pattern>
</filter-mapping>
which of following
component plays role of
Controller in Struts MVC?
1. JSP 2. Servlet 3.
Filter

:
-How to define action
and it’s mapping in
struts.xml?
<action name=“s
earchStudent” class=“c
om.pga.SearchStudentH
andler”>
</action>
In this example,
request(action)
“searchStudent” is
mapped to action
class/model
SearchStudentHandler.

How to map result


name to actual view?
<action name=“s
earchStudent” class="co
m.pga.SearchStudentHa
ndler">
⁃ <result nam
e="success">
display.jsp</res
ult>

</action>
In this, whenever
model/action class
SearchStudnetHanlder
returns result name as
“success”, then that
result will be be passed
to view “display.jsp”.

Note: Model class


always returns result
name and actual view
name is mentioned in
struts.xml file.

How to write Action


class(Model):
1. using POJO class: (execute
method has to be there which
return result name)
class Student {
private int id;
private String name;
private float marks;

//constructor
//getter,setter methods

public String execute


(){
return "success"; /
/returning result name
}
}
2. By implementing Action
interface and overriding execute()
method Action interface.

public class 
LoginAction implements 
Action {
public String execut
e(){
return "success"; /
/returning result name
}
}

3. By extending
ActionSupport class
4. Annotating class with
@Action, @Actions,
@Result
<package name="user" 
namespace="/User" 
extends="struts­default">
<action name="home">

<result>/login.jsp</result>
</action>
<action name="login" 
class="com.journaldev.struts2.a
ction.LoginAction">
<result 
name="SUCCESS">/welcome.jsp</re
sult>
<result 
name="ERROR">/error.jsp</result
>
</action>

</package>

Steps for writing Struts


application:
1. Copy required libraries into
Project/WebContent/WEB-INF/lib
2. Make entry of controller filter
(StrutsPrepareAndExecute
Filter) in web.xml file. 3.
Create “classes” folder inside
WEB-INF directory
4. Create “struts.xml” file under
“/classes” folder.
5. In struts.xml file define
mapping between action and it’s
handler(Action class/View)
6. Define Action class with
method
public String execute( ) { }
- This method returns name
of “result” and result name is
mapped to actual view in
struts.xml file.
Application 1:
Create form to accept user name
()

1st action: input -


mapped to input.jsp
input.jsp contains UI
code with field “num” and
submit button
on clicking submit
button -> action
“checkOddEven” will be
invoked.
Action checkOddEven is
mapped to Model
CheckOddEvenAction
In CheckOddEvenAction
we have business logic to
check odd/even
If number is odd - “odd”
result is returned which is
mapped to “odd.jsp” in
struts.xml
If number is even -
“even” result is returned
which is mapped to
“even.jsp” in struts.xml
mkyong
Steps for writing
annotation
based struts
application
- Define filter in
web.xml file.
- Add lib struts2-
convention-
plugin-2.3.24.1
and it’s
dependenices(a
sm)
- Declare
package with
one of the word
in
it(action,actions
,struts,struts2)
- Declare action
class which
implements
interface
“com.opensymphony.xwork2.A
ction”

- Specify
annotations in
Action class as
below:
@Action(value="welcome")
@ResultPath(value="/")
@Result(name="success",
location="sayWelcome.jsp")
http://localhos
t:8080/Struts
Annotation/ho
me.jsp

http://localhost:8
080/StrutsAnnot
ation/welcome.a
ction
Welcome PGA j2ee
Spring
framework:
Download Spring lib:
http://repo.spring.io/rele
ase/org/springframewor
k/spring/4.3.6.RELEASE/
OR
Use build tool Maven with
following entry in pom.xml file:

<dependencies>
<dependency>

<groupId>org.springframework
</groupId>
<artifactId>spring-
context</artifactId>

<version>4.3.6.RELEASE</versi
on>
</dependency>
</dependencies>
Spring Modules:

1. Spring Core
module :
- IoC (Inversion of
Control) OR
DI(Dependency
Injection)
- Beans
- Core, Context

2. Spring DAO module:


(Database layer)

- Spring +
JDBCTemplate
- Spring + ORM
(Hibernate)

3. Spring Web module


- Spring MVC model

4. Spring AOP(Aspect
Oriented
programming)

Instantiating bean with


constructor argument:
<constructor-arg>

By default beans
declared in
configuration file are
created in advance
whenever spring
framework is
initialized(Eager
initialisation)

If we want some
beans to be
instantiated only when
Java program call
getBean( ), then we
have to use an
attribute lazy-
init="true" in bean
declaration as below.
<bean id="date"
class="java.util.Date" lazy-
init="true”/>
<bean id="stud"
class="com.pga.Student"
lazy-init="true”>
<property
name="rollNo" value="5"
/>
<property
name="name"
value="Fred" />
<property
name="marks" value="80"
/>
</bean>

IMP: All beans declared


inside configuration files
are Singleton (Created
only one time and same
copy of object is given
to Java program
whenever getBean( ) is
called”.

What if we want new


copy of an object
always?
Solution: declare scope
as “prototype”

How to get bean in Java


program?
- Using ID
- Using class name
e.g. Emp e1 = (Emp)
ctx.getBean(com.pga.Em
p.class);

Dependency
Injection:
- DI is used when we
have two classes and
there is dependency
between them.
- There are two ways
to achieve
dependency
injection:
1. Setter based
dependency injection
2. Constructor
based dependency
injection

Example of Setter
based DI:

Injecting Collection:
set, list, map, props

class Emp {
int id;
String name;
Set<String>
technologies;
}

<bean id=“emp”
class=“com.pga.Emp
”>
<property
name=“id”
value=“5”/>
<property
name=“name”
value=“John”/>

</bean>

Injecting array of
objects:

Bean Inheritance

Bean post
processors:
We can write a Java
class which
implements interface
BeanPostProcessor with
2 methods as below:

Module 2: Spring
DAO(Data access
object) - Interacting
with DBMS

- Using
JdbcTemplate
(Spring +
JdbcTemplate)
- Using ORM (Spring
+ Hibernate)

- JDBCTemplate is
dependent on
DataSource.
- Data source is
cerated by specifying
all DBMS related
properties(username,
password,driver,url)
Steps for writing
Spring +
JDBCTemplate
application:
- Add required libs
(lib required for core
+ jdbc + tx + JDBC
driver file)
- Define POJO class
(Class with fields
matches to table
fields)
- Define Dao
class(e.g.
StudentDao) with
“JdbcTemplate”
object as member of
class. Add setter
method for
JdbcTemplate.
- Define all DB
related methods
(add,delete,update,se
lect) in Dao class
- Define following
beans in beans.xml
file 1. DataSource
bean with properties
“username,password,
driverClassName,url”
.

(DriverManagerDataS
ource is one of the
DataSource)
2. JdbcTemplate
bean which depends
on DataSource
3. Dao bean
(StudentDao) which
depends on
JdbcTemplate
- Declare demo
class which initlizes
spring framework
and obtain Dao bean
to call some
method(add/update/d
el/select)

NamedParameterJdbc
Template Demo:
1. Defining EmpDao
interface

hibernate.cfg.xml
- JDBC related
properties
(Drivername,user,pw
d,url)
- dialect, list of
mapping files

xmlns:tx="http://www.springfra
mework.org/schema/tx"
http://www.springframework.or
g/schema/tx

<beans
xmlns="http://www.springframe
work.org/schema/beans"

xmlns:xsi="http://www.w3.org/
2001/XMLSchema-instance"

xmlns:tx="http://www.springfra
mework.org/schema/tx"

xsi:schemaLocation="http://ww
w.springframework.org/schema/
beans

http://www.springframework.or
g/schema/beans/spring-beans-
3.0.xsd

http://www.springframework.or
g/schema/tx
http://www.springframework.or
g/schema/tx/spring-tx-
2.0.xsd">
<tx:annotation-driven/>

Spring4 + Hibernate5
(ORM)
- What all libraries are
needed?
- Define following
beans in beans.xml
file.
1. DataSource bean
(DriverManagerDataSource
) with 4
properties(username,pass
word,url,driverClassName)
2. Define
LocalSessionFactoryBean(
org.springframework.orm.hiber
nate5.LocalSessionFactoryBean
)
with following
properties:
- dataSource(We
already created in first
step, give it’s reference)
-
hibernateProperties
(Property collection with
fields hibernate.dialect,
hibernate.show_sql)
- mappingResources
(Hibernate mapping .hbm
files)
3. Define Dao bean by
giving reference of
sessionFactory created
above.
4. Declare
TransactionManager bean
by given dependency on
sessionFactory as below
<bean
id="transactionManager"

class="org.springframework.or
m.hibernate5.HibernateTransac
tionManager">
<property
name="sessionFactory"
ref="mySessionFactory" />
5. Declare
<tx:annotation-driven/>
tag.
Working example of
beans.xml:

If we specify dependancy
using @Atuowired and if
that bean is not exist
then creation of bean will
failed due to lack of
dependent bean.
Now what if we want to
continue creating bean
even if dependency is not
resolved then you can
auto-wire using following:
@Autowired(required=false)
Bean init-method and
destroy-method
attributes:

init-method : We can
specify method name
which will be called on
bean creation.
destroy-method : We
can specify method
which will be called
when bean is destroyed.

Anda mungkin juga menyukai