59
Java 2 Enterprise Edition SSH Frameworks Presenter : Lee, Gun 2007-02-05 Updated

Java 2 Enterprise Edition SSH Frameworks

  • Upload
    talib

  • View
    68

  • Download
    0

Embed Size (px)

DESCRIPTION

Java 2 Enterprise Edition SSH Frameworks. Presenter : Lee, Gun 2007-02-05 Updated. 1. Model 1 VS Model 2. Struts Introduction. 2. Hibernate Introduction. Integration Of SSH. 3. 5. Spring Introduction. System Logging. 4. 6. Agenda. Process for running JSP. JSP File. Request. Web - PowerPoint PPT Presentation

Citation preview

Page 1: Java 2 Enterprise Edition SSH  Frameworks

Java 2 Enterprise Edition SSH Frameworks

Java 2 Enterprise Edition SSH Frameworks

Presenter : Lee, Gun2007-02-05 Updated

Page 2: Java 2 Enterprise Edition SSH  Frameworks

Agenda

Model 1 VS Model 21

Struts Introduction2

Hibernate Introduction3

Spring Introduction4

Integration Of SSH5

System Logging6

Page 3: Java 2 Enterprise Edition SSH  Frameworks

Process for running JSP

WebBrowser

JSP File

Servlet Source Code

Compiled Servlet Class

Request

Response

Page 4: Java 2 Enterprise Edition SSH  Frameworks

MVC 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.

Page 5: Java 2 Enterprise Edition SSH  Frameworks

Simple Model

Web Brower JSP Database

Request

Response

Modify Data

Read Data

Page 6: Java 2 Enterprise Edition SSH  Frameworks

Model 1 Architecture

Web

Bro

wse

r

JSP

JavaBeans

Database

ApplicationServer

(EJB Server)

Request

Response

Web Server

Ap

plica

tion

Serv

er &

D

ata

base

Page 7: Java 2 Enterprise Edition SSH  Frameworks

Model 2 Architecture

Web

Bro

wse

r

Servlet (Controller)

Database

ApplicationServer

(EJB Server)

Request

Response

Web Server

Ap

plica

tion

Serv

er &

D

ata

base

JSP(View)

JavaBeans(Model)

Page 8: Java 2 Enterprise Edition SSH  Frameworks

Struts 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.

Page 9: Java 2 Enterprise Edition SSH  Frameworks

Struts for MVC Model

Web

Bro

wse

r

Java BeanEJB

(Model)

WebServer

Action Servlet(Controller)

JSP(View)

web.xml

Action(Business Logic)

Action Form(Java Bean Or EJB)

Other Action

Struts-config.xml

Page 10: Java 2 Enterprise Edition SSH  Frameworks

Several 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

Page 11: Java 2 Enterprise Edition SSH  Frameworks

Configuration in web.xml

<servlet> <servlet-name>action</servlet-name> <servlet-

class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param> <param-name>config</param-name>

<param-value>/WEB-INF/config/struts-config.xml</param-value>

</init-param> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>

Page 12: Java 2 Enterprise Edition SSH  Frameworks

Action 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.

Page 13: Java 2 Enterprise Edition SSH  Frameworks

Example 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; }}

Page 14: Java 2 Enterprise Edition SSH  Frameworks

Action 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.

Page 15: Java 2 Enterprise Edition SSH  Frameworks

Action 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.

Page 16: Java 2 Enterprise Edition SSH  Frameworks

Example 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");

}}

Page 17: Java 2 Enterprise Edition SSH  Frameworks

DAO (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.

Page 18: Java 2 Enterprise Edition SSH  Frameworks

Tag 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

Page 19: Java 2 Enterprise Edition SSH  Frameworks

Tag 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.

Page 20: Java 2 Enterprise Edition SSH  Frameworks

Sample of Struts Tag Library

<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>

<%@ taglib uri="http://jakarta.apache.org/struts/tags-logic" prefix="logic" %>

<logic:iterate name="books" type="org.library.bean.Book" id="book">

<tr><%-- book informations --%><td> <bean:write name="book" property="author" /> </td>

</td></logic:iterate>

Page 21: Java 2 Enterprise Edition SSH  Frameworks

Configuration in struts-config.xml

<struts-config> <data-sources /> <form-beans/> <global-exceptions /> <global-forwards/> <!-- Action Mappings --> <action-mappings>

<action forward="/WEB-INF/jsp/index.jsp" path="/default" />

</action-mappings> <!-- Message Resources Configuration --> <message-resources

parameter="org.research.struts.ApplicationResources" />

</struts-config>

Page 22: Java 2 Enterprise Edition SSH  Frameworks

What 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.

Page 23: Java 2 Enterprise Edition SSH  Frameworks

What does Hibernate do?

OO based modelQuery language similar to SQLTransparent Write-behindAdvanced Cache StrategyOptimized SQLFine grained object mappingVendor Abstraction and IndependenceImproves performance by caching, lazy

loading and etc

Page 24: Java 2 Enterprise Edition SSH  Frameworks

Hibernate Architecture

Transient Objects Business Layer

Session Factory

Transaction Factory

ConnectionProvider

Session Transaction

Persistence Layer

Persistence Objects

JNDI JDBC JTA

Hibernate API J2EE API

Page 25: Java 2 Enterprise Edition SSH  Frameworks

Mechanism for Hibernate

Read the hbm.xml during the runtimeRead the class which was included in

hbm.xmlAuto Create SQL after read the stuff on the

aboveCreate proxy class dynamically using the

CGLIB, and then put SQL in it

Page 26: Java 2 Enterprise Edition SSH  Frameworks

Mechanism 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.

Page 27: Java 2 Enterprise Edition SSH  Frameworks

A 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; }}

Page 28: Java 2 Enterprise Edition SSH  Frameworks

A simple Hibernate XML mapping

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-

2.0.dtd"><hibernate-mapping> <classname="hello.Message"table="MESSAGES"> <property name="text"

column="MESSAGE_TEXT"/> <many-to-one name="nextMessage"

cascade="all" column="NEXT_MESSAGE_ID"/>

</class></hibernate-mapping>

Page 29: Java 2 Enterprise Edition SSH  Frameworks

A sample for Hibernate DAO Interface

package org.research.symposium.dao;

import java.util.List;import

org.research.symposium.model.ResearchDepartment;

public interface ResearchDepartmentDAO {public void save(ResearchDepartment transientInstance);public void delete(ResearchDepartment persistentInstance);public ResearchDepartment findById(java.lang.Integer id);public List findByExample(ResearchDepartment instance);

}

Page 30: Java 2 Enterprise Edition SSH  Frameworks

A sample for Hibernate DAO

public void delete(ResearchDepartment persistentInstance) {

log.debug("deleting ResearchDepartment instance");

try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } }

Page 31: Java 2 Enterprise Edition SSH  Frameworks

The 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.

Page 32: Java 2 Enterprise Edition SSH  Frameworks

The 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.

Page 33: Java 2 Enterprise Edition SSH  Frameworks

Summery of Spring Framework

Spring AOP

Aspect OrientedProgramming

Spring ORMHibernate Support

JDO Support

Spring DAOJDBC SupportDAO Support

Spring WebWeb Application

Context

Spring ContextUI SupportValidation

EJB Support

Spring WebMVC

Web MVC FrameworkWeb Views

JSP / VelocityPDF / Excel

Spring CoreSupporting Utilities

Bean Container

Page 34: Java 2 Enterprise Edition SSH  Frameworks

What is IoC?

IoC is short of Inversion of Control.

Lister

finder

listByID

InterfaceFinder

finderByID

FinderWithConstruct

listObjectName

FinderWithConstructfinderByID

<implements>

<<create>>

private Finder finder = new FinderWithConstruct();

Page 35: Java 2 Enterprise Edition SSH  Frameworks

What is AOP?

Check Point

Injector

Separation of Aspect Combination of Aspect

Security Logging Tran Mgmt

Page 36: Java 2 Enterprise Edition SSH  Frameworks

Spring Middle Tiles

Spring AOP Spring ORM

Spring Core Spring DAO

Transaction ManagementUsing Spring decl. trans

Hibernate MappingsCustom Hibernate DAOs

Spring WEB

Web fronted usingStruts or WebWork

Page 37: Java 2 Enterprise Edition SSH  Frameworks

SSH Architecture

Spring Container

Struts Framework

Spring Framework

Hibernate Framework

Servlet Container

UI (User Interface) Layer

Business Layer

Persistence Layer

Page 38: Java 2 Enterprise Edition SSH  Frameworks

SSH Framework - Struts

Web

Bro

wse

r

Sp

ring

WebServer

Action Servlet(Controller)

JSP(View)

web.xml

Action(Business Logic)

Action Form(Java Bean Or EJB)

Other Action

Struts-config.xml

S S

Hib

ern

ate

H

Page 39: Java 2 Enterprise Edition SSH  Frameworks

SSH Framework - Spring

Web

Bro

wse

r

S S

Hib

ern

ate

H

Stru

ts

Action(Business Logic)

Action Form(Java Bean Or EJB)

Other Action

ApplicationContext.xml

AbstractService

ServiceImpl

Page 40: Java 2 Enterprise Edition SSH  Frameworks

SSH Framework - Hibernate

Web

Bro

wse

r

S S H

Stru

ts

Sp

ring

AbstractDAO

DAOImpl

XXX.hbm.xml

AbstractModel

ModelImpl

Page 41: Java 2 Enterprise Edition SSH  Frameworks

Spring 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.

Page 42: Java 2 Enterprise Edition SSH  Frameworks

Spring integration with Struts (Cont.)

Delegation method of Spring integration<action path="/searchSubmit"

type="org.springframework.web.struts.DelegatingActionProxy"

input="/searchEntry.do"

name="searchForm">

</action>

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/>

</plug-in>

Page 43: Java 2 Enterprise Edition SSH  Frameworks

Spring integration with Struts (Cont.)

Register a Struts action in the Spring context…<beans> <bean name="/searchSubmit" class="ca.nexcel.books.actions.SearchSubmit"> <property name="bookService"> <ref bean="bookService"/> </property> </bean></beans>…

Page 44: Java 2 Enterprise Edition SSH  Frameworks

Spring 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

Page 45: Java 2 Enterprise Edition SSH  Frameworks

Spring integration with Hibernate (Cont.)

Configuring the Hibernate SessionFactory in Spring<bean id="sessionFactory"

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

<property name="mappingResources"> <list>

<value>com/zabada/springrecipes/base/Widget.hbm.xml

</value> </list> </property> </bean>

Page 46: Java 2 Enterprise Edition SSH  Frameworks

Extending HibernateDaoSupport for the Actual DAO Implementation.public class WidgetDAOHibernateImpl extends HibernateDaoSupport implements WidgetDAO { public Collection getWidgets() { return getHibernateTemplate().loadAll(Widget.class); } public Widget saveWidget(Widget widget) { getHibernateTemplate().saveOrUpdate(widget); return widget; }}

Spring integration with Hibernate (Cont.)

Page 47: Java 2 Enterprise Edition SSH  Frameworks

Spring integration with Hibernate (Cont.)

Using AOP to Wire Up the DAO and Transaction Management<bean id="hibernateInterceptor"class="org.springframework.orm.hibernate3.HibernateIn

terceptor"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property></bean><bean id="widgetDaoTarget"class="com.zabada.springrecipes.hibernate.WidgetDAO

HibernateImpl"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property></bean>

Page 48: Java 2 Enterprise Edition SSH  Frameworks

Spring integration with Hibernate (Cont.)

<bean id="widgetDAO"class="org.springframework.aop.framework.ProxyFactor

yBean"> <property name="proxyInterfaces"><value>com.zabada.springrecipes.base.WidgetDAO</

value> </property> <property name="interceptorNames"> <list> <value>hibernateInterceptor</value> <value>widgetDaoTarget</value> </list> </property></bean>

Page 49: Java 2 Enterprise Edition SSH  Frameworks

The 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

Page 50: Java 2 Enterprise Edition SSH  Frameworks

Issues of System.out.println ()

Output format for logging info isn’t 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();

Page 51: Java 2 Enterprise Edition SSH  Frameworks

Logger’s 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.

Page 52: Java 2 Enterprise Edition SSH  Frameworks

Solutions 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.

Page 53: Java 2 Enterprise Edition SSH  Frameworks

Log4j.xml Configuration

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%p - %C{1}.%M(%L) | %m

%n"/> </layout> </appender>

<logger name="org.springframework"> <level value="WARN"/> </logger>

<logger name="com.nanumsem"> <level value="DEBUG"/> </logger>

<root> <level value="WARN"/>

<appender-ref ref="CONSOLE"/> </root></log4j:configuration>

Page 54: Java 2 Enterprise Edition SSH  Frameworks

Log4j DEMO

protected final Log logger = LogFactory.getLog(getClass());if (logger.isDebugEnabled()) {logger.debug("entering 'list' method...");}

Page 55: Java 2 Enterprise Edition SSH  Frameworks

P6SPY

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.

Page 56: Java 2 Enterprise Edition SSH  Frameworks

Integrate P6SPY With Hibernate

<bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName">

<value>com.p6spy.engine.spy.P6SpyDriver</value></property><property name="url">

<value>jdbc:mysql://localhost:3306/</value>

</property><property name="username">

<value>username</value></property><property name="password">

<value>password</value></property>

</bean>

Page 57: Java 2 Enterprise Edition SSH  Frameworks

SQL Profiler DEMO

Page 58: Java 2 Enterprise Edition SSH  Frameworks

Reference

http://www.java.comhttp://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/

Page 59: Java 2 Enterprise Edition SSH  Frameworks