Title: Java 2 Enterprise Edition SSH Frameworks
1Java 2 Enterprise Edition SSH Frameworks
- Presenter Lee, Gun
- 2007-02-05 Updated
2Agenda
3Process for running JSP
JSP File
Request
Web Browser
Servlet Source Code
Response
Compiled Servlet Class
4MVC Introduction
- The Model-View-Controller (MVC) is a commonly
used and powerful architecture for GUIs. - The MVC paradigm is a way of breaking an
application, or even just a piece of an
application's interface, into three parts the
model, the view, and the controller. MVC was
originally developed to map the traditional
input, processing, output roles into the GUI
realm.
5Simple Model
Request
Modify Data
Web Brower
JSP
Database
Response
Read Data
6Model 1 Architecture
Application Server (EJB Server)
Application Server Database
JSP
Request
Web Browser
Response
Database
JavaBeans
Web Server
7Model 2 Architecture
Application Server (EJB Server)
Application Server Database
Servlet (Controller)
Request
Web Browser
Database
JSP (View)
JavaBeans (Model)
Response
Web Server
8Struts Introduction
- The goal of the Apache Struts project is to
encourage application architectures based on the
"Model 2" approach, a variation of the classic
Model-View-Controller (MVC) design paradigm.
Under Model 2, a servlet (or equivalent) manages
business logic execution, and presentation logic
resides mainly in server pages.
9Struts for MVC Model
web.xml
Struts-config.xml
Action Servlet (Controller)
Web Browser
Java Bean EJB (Model)
Action (Business Logic)
Web Server
Action Form (Java Bean Or EJB)
Other Action
JSP (View)
10Several models in Struts
- Model 1
- JSP / Servlet
- JSP Java Bean
- JSP Custom Tag
- Integrate above 3 models
- Model 2
- JSP / Servlet Struts
- JSP Struts JSTL JSF
- JSP Struts Velocity Sitemesh
- Integrate above 3 models
11Configuration in web.xml
- ltservletgt
- ltservlet-namegtactionlt/servlet-namegt
- ltservlet-classgtorg.apache.struts.action.Action
Servletlt/servlet-classgt - ltinit-paramgt
- ltparam-namegtconfiglt/param-namegt
- ltparam-valuegt/WEB-INF/config/struts-config.x
mllt/param-valuegt - lt/init-paramgt
- lt/servletgt
-
- ltservlet-mappinggt
- ltservlet-namegtactionlt/servlet-namegt
- lturl-patterngt.dolt/url-patterngt
- lt/servlet-mappinggt
12Action Form in Struts
- An ActionForm is a JavaBean that extends
org.apache.struts.action.ActionForm. - ActionForm maintains the session state for web
application and the ActionForm object is
automatically populated on the server side with
data entered from a form on the client side.
13Example of Action Form
- public class Message
- private String text
- private Message nextMessage
- public String getText() return text
- public void setText(String text)
- this.text text
- public Message getNextMessage()
- return nextMessage
- public void setNextMessage(Message
nextMessage) - this.nextMessage nextMessage
-
-
14Action in Struts
- The Action Class is part of the Model and is a
wrapper around the business logic. - The purpose of Action Class is to translate the
HttpServletRequest to the business logic. - To use the Action, we need to Subclass and
overwrite the execute() method. - In the Action Class all the database/business
processing are done. - It is advisable to perform all the database
related stuffs in the Action Class.
15Action in Struts (Cont.)
- The ActionServlet (commad) passes the
parameterized class to Action Form using the
execute() method. - The return type of the execute method is
ActionForward which is used by the Struts
Framework to forward the request to the file as
per the value of the returned ActionForward
object.
16Example of Action
- public class SymposiumAction extends
DispatchAction - private SymposiumService symposiumService
null - public void setSymposiumService(SymposiumService
symposiumService) - this.symposiumService symposiumService
-
- public ActionForward list(ActionMapping mapping,
ActionForm form, - HttpServletRequest request, HttpServletResponse
response) - throws Exception
- request.setAttribute("symposiumList",
symposiumService.findSymposiumList()) - return mapping.findForward("list")
-
17DAO (Data Access Object) in Struts
- Access to data varies depending on the source of
the data. - Access to persistent storage, such as to a
database, varies greatly depending on the type of
storage (relational databases, object-oriented
databases, flat files, and so forth) and the
vendor implementation. - We will implement DAO in hibernate persistence
Layer.
18Tag Libraries in Struts
- HTML Tag Lib
- The tags in the Struts HTML library form a bridge
between a JSP view and the other components of a
Web application. - Bean Tag Lib
- Contains JSP custom tags useful in defining new
beans (in any desired scope) from a variety of
possible sources, as well as a tag to render a
particular bean (or bean property) to the output
response. - Logic Tag Lib
- Contains tags that are useful in managing
conditional generation of output text, looping
over object collections for repetitive generation
of output text, and application flow management
19Tag Libraries in Struts (Cont.)
- Nested Tag Lib
- Nested tags supporting classes extend the base
struts tags to allow them to relate to each other
in a nested nature. - Tiles Tag Lib
- Tiles builds on the "include" feature provided by
the JavaServer Pages specification to provide a
full-featured, robust framework for assembling
presentation pages from component parts.
20Sample of Struts Tag Library
- lt_at_ taglib uri"http//jakarta.apache.org/struts/t
ags-bean" prefix"bean"gt - lt_at_ taglib uri"http//jakarta.apache.org/struts/t
ags-html" prefix"html"gt - lt_at_ taglib uri"http//jakarta.apache.org/struts/t
ags-logic" prefix"logic" gt - ltlogiciterate name"books" type"org.library.bean
.Book" id"book"gt - lttrgt
- lt-- book informations --gt
- lttdgt ltbeanwrite name"book" property"author"
/gt lt/tdgt - lt/tdgt
- lt/logiciterategt
21Configuration in struts-config.xml
- ltstruts-configgt
- ltdata-sources /gt
- ltform-beans/gt
- ltglobal-exceptions /gt
- ltglobal-forwards/gt
- lt!-- Action Mappings --gt
- ltaction-mappingsgt
- ltaction forward"/WEB-INF/jsp/index.jsp"
path"/default" /gt - lt/action-mappingsgt
- lt!-- Message Resources Configuration --gt
- ltmessage-resources parameter"org.research.strut
s.ApplicationResources" /gt - lt/struts-configgt
22What is Hibernate?
- Hibernate is a powerful, high performance
object/relational persistence and query service. - Hibernate lets you develop persistent classes
following object-oriented idiom - including
association, inheritance, polymorphism,
composition, and collections.
23What does Hibernate do?
- OO based model
- Query language similar to SQL
- Transparent Write-behind
- Advanced Cache Strategy
- Optimized SQL
- Fine grained object mapping
- Vendor Abstraction and Independence
- Improves performance by caching, lazy loading and
etc
24Hibernate Architecture
Transient Objects
Business Layer
Persistence Objects
Persistence Layer
Session Factory
Session
Transaction
Transaction Factory
Connection Provider
JNDI
JDBC
JTA
Hibernate API
J2EE API
25Mechanism for Hibernate
- Read the hbm.xml during the runtime
- Read the class which was included in hbm.xml
- Auto Create SQL after read the stuff on the above
- Create proxy class dynamically using the CGLIB,
and then put SQL in it
26Mechanism for Hibernate (Cont.)
- Call the session object, when user access
persistency objects - save(Object aPersistentObject)
- delete(Object aPersistentObject)
- update(Object aPersistentObject)
- Each call retrieve to SQL via proxy class, and
send to RDB.
27A sample for Persistent class
- public class Message
- private String text
- private Message nextMessage
- public String getText() return text
- public void setText(String text)
- this.text text
- public Message getNextMessage()
- return nextMessage
- public void setNextMessage(Message
nextMessage) - this.nextMessage nextMessage
-
28A simple Hibernate XML mapping
- lt?xml version"1.0"?gt
- lt!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN" - "http//hibernate.sourceforge.net/hibernate-mappin
g-2.0.dtd"gt - lthibernate-mappinggt
- ltclassname"hello.Message"table"MESSAGES"gt
- ltproperty name"text" column"MESSA
GE_TEXT"/gt - ltmany-to-one name"nextMessage"
cascade"all" - column"NEXT_MESSAGE_ID"/gt
- lt/classgt
- lt/hibernate-mappinggt
29A sample for Hibernate DAO Interface
- package org.research.symposium.dao
- import java.util.List
- import org.research.symposium.model.ResearchDepart
ment - public interface ResearchDepartmentDAO
- public void save(ResearchDepartment
transientInstance) - public void delete(ResearchDepartment
persistentInstance) - public ResearchDepartment findById(java.lang.Inte
ger id) - public List findByExample(ResearchDepartment
instance)
30A sample for Hibernate DAO
- public void delete(ResearchDepartment
persistentInstance) - log.debug("deleting ResearchDepartment
instance") - try
- getHibernateTemplate().delete(persistentI
nstance) - log.debug("delete successful")
- catch (RuntimeException re)
- log.error("delete failed", re)
- throw re
-
-
31The benefits of Spring
- Spring can effectively organize your middle tier
objects, whether or not you choose to use EJB. - Spring can eliminate the proliferation of
Singletons seen on many projects. - Applications built using Spring are very easy to
unit test.
32The benefits of Spring (Cont.)
- Spring helps you solve many problems without
using EJB. - Spring provides a consistent framework for data
access, whether using JDBC or an O/R mapping
product such as Hibernate or a JDO implementation.
33Summery of Spring Framework
Spring AOP Aspect Oriented Programming
Spring ORM Hibernate Support JDO Support
Spring Web Web Application Context
Spring Web MVC Web MVC Framework Web Views JSP /
Velocity PDF / Excel
Spring DAO JDBC Support DAO Support
Spring Context UI Support Validation EJB Support
Spring Core Supporting Utilities Bean Container
34What is IoC?
- IoC is short of Inversion of Control.
Interface Finder
Lister
finder
finderByID
listByID
ltimplementsgt
FinderWithConstruct
ltltcreategtgt
listObjectName
FinderWithConstruct finderByID
private Finder finder new FinderWithConstruct()
35What is AOP?
Check Point
Injector
Combination of Aspect
Separation of Aspect
Security
Logging
Tran Mgmt
36Spring Middle Tiles
Web fronted using Struts or WebWork
Spring WEB
Spring AOP
Spring ORM
Transaction Management Using Spring decl. trans
Hibernate Mappings Custom Hibernate DAOs
Spring Core
Spring DAO
37SSH Architecture
Spring Container
Servlet Container
Struts Framework
UI (User Interface) Layer
Spring Framework
Business Layer
Hibernate Framework
Persistence Layer
38SSH Framework - Struts
Spring
Struts-config.xml
Hibernate
web.xml
Action Servlet (Controller)
Web Browser
Action (Business Logic)
Web Server
Action Form (Java Bean Or EJB)
Other Action
JSP (View)
S
S
H
39SSH Framework - Spring
Hibernate
Struts
Action (Business Logic)
ServiceImpl
Web Browser
Action Form (Java Bean Or EJB)
AbstractService
Other Action
ApplicationContext.xml
S
S
H
40SSH Framework - Hibernate
Struts
Spring
DAOImpl
ModelImpl
Web Browser
AbstractDAO
AbstractModel
XXX.hbm.xml
S
S
H
41Spring integration with Struts
- Use Spring's ActionSupport
- Override the RequestProcessor
- Delegate action management to Spring
- A much better solution is to delegate Struts
action management to the Spring framework. - You can do this by registering a proxy in the
struts-config action mapping. - The proxy is responsible for looking up the
Struts action in the Spring context. - Because the action is under Spring's control, it
populates the action's JavaBean properties and
leaves the door open to applying features such as
Spring's AOP interceptors.
42Spring integration with Struts (Cont.)
- Delegation method of Spring integration
- ltaction path"/searchSubmit"
type"org.springframework.web.struts.DelegatingAct
ionProxy" - input"/searchEntry.do"
- name"searchForm"gt
- lt/actiongt
- ltplug-in className"org.springframework.web.struts
.ContextLoaderPlugIn"gt ltset-property
property"contextConfigLocation"
value"/WEB-INF/beans.xml"/gt - lt/plug-ingt
43Spring integration with Struts (Cont.)
- Register a Struts action in the Spring context
-
- ltbeansgt
- ltbean name"/searchSubmit"
- class"ca.nexcel.books.actions.SearchSubmi
t"gt - ltproperty name"bookService"gt
- ltref bean"bookService"/gt
- lt/propertygt
- lt/beangt
- lt/beansgt
44Spring integration with Hibernate
- Two approaches
- Inversion of Control with a HibernateTemplate and
Callback. - Extending HibernateDaoSupport and Applying an AOP
Interceptor. - Configure the Hibernate SessionFactory
- Extend your DAO Implementation from
HibernateDaoSupport - Wire in Transaction Support with AOP
45Spring integration with Hibernate (Cont.)
- Configuring the Hibernate SessionFactory in
Spring - ltbean id"sessionFactory" class"org.springframewo
rk.orm.hibernate3.LocalSessionFactoryBean"gt - ltproperty name"mappingResources"gt
- ltlistgt ltvaluegtcom/zabada/springrecipes/base/Widget
.hbm.xml - lt/valuegt
- lt/listgt
- lt/propertygt
- lt/beangt
46Spring integration with Hibernate (Cont.)
- Extending HibernateDaoSupport for the Actual DAO
Implementation. - public class WidgetDAOHibernateImpl
- extends HibernateDaoSupport
- implements WidgetDAO
- public Collection getWidgets()
-
- return getHibernateTemplate().loadAll(Widget.c
lass) -
- public Widget saveWidget(Widget widget)
-
- getHibernateTemplate().saveOrUpdate(widget)
- return widget
-
47Spring integration with Hibernate (Cont.)
- Using AOP to Wire Up the DAO and Transaction
Management - ltbean id"hibernateInterceptor"
- class"org.springframework.orm.hibernate3.Hibernat
eInterceptor"gt - ltproperty name"sessionFactory"gt
- ltref bean"sessionFactory"/gt
- lt/propertygt
- lt/beangt
- ltbean id"widgetDaoTarget"
- class"com.zabada.springrecipes.hibernate.WidgetDA
OHibernateImpl"gt - ltproperty name"sessionFactory"gt
- ltref bean"sessionFactory"/gt
- lt/propertygtlt/beangt
48Spring integration with Hibernate (Cont.)
- ltbean id"widgetDAO"
- class"org.springframework.aop.framework.ProxyFact
oryBean"gt - ltproperty name"proxyInterfaces"gt
- ltvaluegtcom.zabada.springrecipes.base.WidgetDAOlt/va
luegt - lt/propertygt
- ltproperty name"interceptorNames"gt
- ltlistgt
- ltvaluegthibernateInterceptorlt/valuegt
- ltvaluegtwidgetDaoTargetlt/valuegt
- lt/listgt
- lt/propertygt
- lt/beangt
49The Packaging for the Whole Project
- WebRoot
- WEB-INF
- Classes
- Config (applicationContext.xml,
struts-config.xml) - Jsp (JSP Files)
- Lib (Struts, Spring, Hibernate Libs)
- Tld (Tlds for JSTL or struts)
- Validator (validator-rules.xml validation.xml)
- META-INF
- MANIFEST.MF
50Issues of System.out.println ()
- Output format for logging info isnt so flexible.
- Programmer has to recompile the source if there
has some changes. - The efficiency of application can be decrease if
there are so many println()
51Loggers Level
- Off The OFF Level has the highest possible rank
and is intended to turn off logging. - Fatal The FATAL level designates very severe
error events that will presumably lead the
application to abort. - Error The ERROR level designates error events
that might still allow the application to
continue running. - Warn The WARN level designates potentially
harmful situations. - Info The INFO level designates informational
messages that highlight the progress of the
application at coarse-grained level. - Debug The DEBUG Level designates fine-grained
informational events that are most useful to
debug an application. - All The ALL Level has the lowest possible rank
and is intended to turn on all logging.
52Solutions for managing Log4j
- User can enable, disable and switch the logging
level between (INFO, WARN, DEBUG, ERROR, FATAL,
OFF, ALL) the various levels at run-time in my
web application.
53Log4j.xml Configuration
- lt?xml version"1.0" encoding"UTF-8" ?gt
- lt!DOCTYPE log4jconfiguration SYSTEM "log4j.dtd"gt
- ltlog4jconfiguration xmlnslog4j"http//jakarta.a
pache.org/log4j/"gt - ltappender name"CONSOLE" class"org.apache.log
4j.ConsoleAppender"gt - ltlayout class"org.apache.log4j.PatternLay
out"gt - ltparam name"ConversionPattern"
value"p - C1.M(L) mn"/gt - lt/layoutgt
- lt/appendergt
- ltlogger name"org.springframework"gt
- ltlevel value"WARN"/gt
- lt/loggergt
- ltlogger name"com.nanumsem"gt
- ltlevel value"DEBUG"/gt
- lt/loggergt
- ltrootgt
- ltlevel value"WARN"/gt
54Log4j DEMO
- protected final Log logger LogFactory.getLog(get
Class()) - if (logger.isDebugEnabled())
-
- logger.debug("entering 'list' method...")
55P6SPY
- P6Log intercepts and logs the database statements
of any application that uses JDBC. - This application is particularly useful for
developers to monitor the SQL statements produced
by EJB servers Or ORM. - P6Spy is designed to be installed in minutes and
requires no code changes.
56Integrate P6SPY With Hibernate
- ltbean id"dataSource"
- class"org.apache.commons.dbcp.BasicDataSource"gt
- ltproperty name"driverClassName"gt
- ltvaluegtcom.p6spy.engine.spy.P6SpyDriverlt/valuegt
- lt/propertygt
- ltproperty name"url"gt
- ltvaluegtjdbcmysql//localhost3306/lt/v
aluegt - lt/propertygt
- ltproperty name"username"gt
- ltvaluegtusernamelt/valuegt
- lt/propertygt
- ltproperty name"password"gt
- ltvaluegtpasswordlt/valuegt
- lt/propertygt
- lt/beangt
57SQL Profiler DEMO
58Reference
- http//www.java.com
- http//struts.apache.org/
- http//sourceforge.net/
- http//db.apache.org/ojb/
- http//logging.apache.org/log4j/
- http//jakarta.apache.org/velocity/
- http//jakarta.apache.org/commons/
- http//www.hibernate.org/
- http//www.springframework.org/
- http//www.p6spy.com/
59Thank You !