Java 2 Enterprise Edition SSH Frameworks Presenter Lee

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

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

Agenda 1 Model 1 VS Model 2 2 Struts Introduction 3 Hibernate Introduction 4

Agenda 1 Model 1 VS Model 2 2 Struts Introduction 3 Hibernate Introduction 4 Spring Introduction 5 Integration Of SSH 6 System Logging

Process for running JSP File st e u eq R Web Browser Servlet Source

Process for running JSP File st e u eq R Web Browser Servlet Source Code Res pon se Compiled Servlet Class

MVC Introduction v The Model-View-Controller (MVC) is a commonly used and powerful architecture for

MVC Introduction v The Model-View-Controller (MVC) is a commonly used and powerful architecture for GUIs. v 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.

Simple Model Request Web Brower Modify Data JSP Response Database Read Data

Simple Model Request Web Brower Modify Data JSP Response Database Read Data

Model 1 Architecture Web Browser JSP Response Application Server (EJB Server) Java. Beans Database

Model 1 Architecture Web Browser JSP Response Application Server (EJB Server) Java. Beans Database Web Server Application Server & Database Request

Model 2 Architecture Web Browser Servlet (Controller) Response JSP (View) Java. Beans (Model) Web

Model 2 Architecture Web Browser Servlet (Controller) Response JSP (View) Java. Beans (Model) Web Server Application Server (EJB Server) Database Application Server & Database Request

Struts Introduction v The goal of the Apache Struts project is to encourage application

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

Struts for MVC Model Web Browser web. xml Struts-config. xml Action Servlet (Controller) Action

Struts for MVC Model Web Browser web. xml Struts-config. xml Action Servlet (Controller) Action Web Server (Business Logic) Action Form (Java Bean Or EJB) JSP (View) Other Action Java Bean EJB (Model)

Several models in Struts v Model 1 § JSP / Servlet § JSP +

Several models in Struts v Model 1 § JSP / Servlet § JSP + Java Bean § JSP + Custom Tag § Integrate above 3 models v Model 2 § JSP / Servlet + Struts § JSP + Struts + JSTL + JSF § JSP + Struts + Velocity + Sitemesh § Integrate above 3 models

Configuration in web. xml <servlet> <servlet-name>action</servlet-name> <servletclass>org. apache. struts. action. Action. Servlet</servlet -class> <init-param>

Configuration in web. xml <servlet> <servlet-name>action</servlet-name> <servletclass>org. apache. struts. action. Action. Servlet</servlet -class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/config/strutsconfig. xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*. do</url-pattern> </servlet-mapping>

Action Form in Struts v An Action. Form is a Java. Bean that extends

Action Form in Struts v An Action. Form is a Java. Bean that extends org. apache. struts. action. Action. Form. v Action. Form maintains the session state for web application and the Action. Form object is automatically populated on the server side with data entered from a form on the client side.

Example of Action Form public class Message { private String text; private Message next.

Example of Action Form public class Message { private String text; private Message next. Message; public String get. Text() {return text; } public void set. Text(String text) { this. text = text; } public Message get. Next. Message() { return next. Message; } public void set. Next. Message(Message next. Message) { this. next. Message = next. Message; } }

Action in Struts v The Action Class is part of the Model and is

Action in Struts v The Action Class is part of the Model and is a wrapper around the business logic. v The purpose of Action Class is to translate the Http. Servlet. Request to the business logic. v To use the Action, we need to Subclass and overwrite the execute() method. v In the Action Class all the database/business processing are done. v It is advisable to perform all the database related stuffs in the Action Class.

Action in Struts (Cont. ) v The Action. Servlet (commad) passes the parameterized class

Action in Struts (Cont. ) v The Action. Servlet (commad) passes the parameterized class to Action Form using the execute() method. v The return type of the execute method is Action. Forward which is used by the Struts Framework to forward the request to the file as per the value of the returned Action. Forward object.

Example of Action public class Symposium. Action extends Dispatch. Action { private Symposium. Service

Example of Action public class Symposium. Action extends Dispatch. Action { private Symposium. Service symposium. Service = null; public void set. Symposium. Service(Symposium. Service symposium. Service) { this. symposium. Service = symposium. Service; } public Action. Forward list(Action. Mapping mapping, Action. Form form, Http. Servlet. Request request, Http. Servlet. Response response) throws Exception { request. set. Attribute("symposium. List", symposium. Service. find. Symposium. List()); return mapping. find. Forward("list"); } }

DAO (Data Access Object) in Struts v Access to data varies depending on the

DAO (Data Access Object) in Struts v Access to data varies depending on the source of the data. v 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. v We will implement DAO in hibernate persistence Layer.

Tag Libraries in Struts v HTML Tag Lib § The tags in the Struts

Tag Libraries in Struts v 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. v 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. v 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

Tag Libraries in Struts (Cont. ) v Nested Tag Lib § Nested tags &

Tag Libraries in Struts (Cont. ) v Nested Tag Lib § Nested tags & supporting classes extend the base struts tags to allow them to relate to each other in a nested nature. v Tiles Tag Lib § Tiles builds on the "include" feature provided by the Java. Server Pages specification to provide a fullfeatured, robust framework for assembling presentation pages from component parts.

Sample of Struts Tag Library <%@ taglib uri="http: //jakarta. apache. org/struts/tagsbean" prefix="bean"%> <%@ taglib

Sample of Struts Tag Library <%@ taglib uri="http: //jakarta. apache. org/struts/tagsbean" prefix="bean"%> <%@ taglib uri="http: //jakarta. apache. org/struts/tagshtml" prefix="html"%> <%@ taglib uri="http: //jakarta. apache. org/struts/tagslogic" prefix="logic" %> <logic: iterate name="books" type="org. library. bean. Book" id="book"> <tr> <%-- book informations --%> <td> <bean: write name="book" property="author" /> </td> </logic: iterate>

Configuration in struts-config. xml <struts-config> <data-sources /> <form-beans/> <global-exceptions /> <global-forwards/> <!-- Action Mappings

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. Application. Resources" /> </struts-config>

What is Hibernate? v Hibernate is a powerful, high performance object/relational persistence and query

What is Hibernate? v Hibernate is a powerful, high performance object/relational persistence and query service. v Hibernate lets you develop persistent classes following object-oriented idiom - including association, inheritance, polymorphism, composition, and collections.

What does Hibernate do? v OO based model v Query language similar to SQL

What does Hibernate do? v OO based model v Query language similar to SQL v Transparent Write-behind v Advanced Cache Strategy v Optimized SQL v Fine grained object mapping v Vendor Abstraction and Independence v Improves performance by caching, lazy loading and etc

Hibernate Architecture Transient Objects Business Layer Persistence Objects Persistence Layer Session Factory Transaction Factory

Hibernate Architecture Transient Objects Business Layer Persistence Objects Persistence Layer Session Factory Transaction Factory Connection Provider JNDI Hibernate API Session JDBC J 2 EE API Transaction JTA

Mechanism for Hibernate v Read the hbm. xml during the runtime v Read the

Mechanism for Hibernate v Read the hbm. xml during the runtime v Read the class which was included in hbm. xml v Auto Create SQL after read the stuff on the above v Create proxy class dynamically using the CGLIB, and then put SQL in it

Mechanism for Hibernate (Cont. ) v Call the session object, when user access persistency

Mechanism for Hibernate (Cont. ) v Call the session object, when user access persistency objects § save(Object a. Persistent. Object); § delete(Object a. Persistent. Object); § update(Object a. Persistent. Object): v Each call retrieve to SQL via proxy class, and send to RDB.

A sample for Persistent class public class Message { private String text; private Message

A sample for Persistent class public class Message { private String text; private Message next. Message; public String get. Text() {return text; } public void set. Text(String text) { this. text = text; } public Message get. Next. Message() { return next. Message; } public void set. Next. Message(Message next. Message) { this. next. Message = next. Message; } }

A simple Hibernate XML mapping <? xml version="1. 0"? > <!DOCTYPE hibernate-mapping PUBLIC "//Hibernate

A simple Hibernate XML mapping <? xml version="1. 0"? > <!DOCTYPE hibernate-mapping PUBLIC "//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="next. Message" cascade="all" column="NEXT_MESSAGE_ID"/> </class> </hibernate-mapping>

A sample for Hibernate DAO Interface package org. research. symposium. dao; import java. util.

A sample for Hibernate DAO Interface package org. research. symposium. dao; import java. util. List; import org. research. symposium. model. Research. Department; public interface Research. Department. DAO { public void save(Research. Department transient. Instance); public void delete(Research. Department persistent. Instance); public Research. Department find. By. Id(java. lang. Integer id); public List find. By. Example(Research. Department instance); }

A sample for Hibernate DAO public void delete(Research. Department persistent. Instance) { log. debug("deleting

A sample for Hibernate DAO public void delete(Research. Department persistent. Instance) { log. debug("deleting Research. Department instance"); try { get. Hibernate. Template(). delete(persistent. Instance ); log. debug("delete successful"); } catch (Runtime. Exception re) { log. error("delete failed", re); throw re; } }

The benefits of Spring v Spring can effectively organize your middle tier objects, whether

The benefits of Spring v Spring can effectively organize your middle tier objects, whether or not you choose to use EJB. v Spring can eliminate the proliferation of Singletons seen on many projects. v Applications built using Spring are very easy to unit test.

The benefits of Spring (Cont. ) v Spring helps you solve many problems without

The benefits of Spring (Cont. ) v Spring helps you solve many problems without using EJB. v Spring provides a consistent framework for data access, whether using JDBC or an O/R mapping product such as Hibernate or a JDO implementation.

Summery of Spring Framework Spring AOP Aspect Oriented Programming Spring ORM Spring Web Hibernate

Summery of Spring Framework Spring AOP Aspect Oriented Programming Spring ORM Spring Web Hibernate Support JDO Support Web Application Context Spring DAO JDBC Support DAO Support Spring Context UI Support Validation EJB Support Spring Core Supporting Utilities Bean Container Spring Web MVC Framework Web Views JSP / Velocity PDF / Excel

What is Io. C? v Io. C is short of Inversion of Control. Lister

What is Io. C? v Io. C is short of Inversion of Control. Lister Interface Finder finder. By. ID list. By. ID <<create>> <implements> Finder. With. Construct list. Object. Name Finder. With. Construct finder. By. ID private Finder finder = new Finder. With. Construct();

What is AOP? Injector Check Point Separation of Aspect Security Logging Combination of Aspect

What is AOP? Injector Check Point Separation of Aspect Security Logging Combination of Aspect Tran Mgmt

Spring Middle Tiles Web fronted using Struts or Web. Work Spring WEB Spring AOP

Spring Middle Tiles Web fronted using Struts or Web. Work Spring WEB Spring AOP Spring ORM Transaction Management Using Spring decl. trans Hibernate Mappings Custom Hibernate DAOs Spring Core Spring DAO

SSH Architecture Spring Container Servlet Container Struts Framework UI (User Interface) Layer Spring Framework

SSH Architecture Spring Container Servlet Container Struts Framework UI (User Interface) Layer Spring Framework Business Layer Hibernate Framework Persistence Layer

SSH Framework - Struts Action Servlet (Controller) Action Web Server Action Form (Java Bean

SSH Framework - Struts Action Servlet (Controller) Action Web Server Action Form (Java Bean Or EJB) JSP (View) S (Business Logic) Hibernate Struts-config. xml Spring Web Browser web. xml Other Action S H

SSH Framework - Spring Action Service. Impl Web Browser Struts Action Form (Java Bean

SSH Framework - Spring Action Service. Impl Web Browser Struts Action Form (Java Bean Or EJB) Abstract. Service Hibernate (Business Logic) Other Action Application. Context. xml S S H

SSH Framework - Hibernate Model. Impl Abstract. DAO Abstract. Model Spring Struts Web Browser

SSH Framework - Hibernate Model. Impl Abstract. DAO Abstract. Model Spring Struts Web Browser DAOImpl XXX. hbm. xml S S H

Spring integration with Struts v Use Spring's Action. Support v Override the Request. Processor

Spring integration with Struts v Use Spring's Action. Support v Override the Request. Processor v 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 strutsconfig 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 Java. Bean properties and leaves the door open to applying features such as Spring's AOP interceptors.

Spring integration with Struts (Cont. ) v Delegation method of Spring integration <action path="/search.

Spring integration with Struts (Cont. ) v Delegation method of Spring integration <action path="/search. Submit" type="org. springframework. web. struts. Delegating. Acti on. Proxy" input="/search. Entry. do" name="search. Form"> </action> <plug-in class. Name="org. springframework. web. struts. Context Loader. Plug. In"> <set-property="context. Config. Location" value="/WEBINF/beans. xml"/> </plug-in>

Spring integration with Struts (Cont. ) v Register a Struts action in the Spring

Spring integration with Struts (Cont. ) v Register a Struts action in the Spring context … <beans> <bean name="/search. Submit" class="ca. nexcel. books. actions. Search. Submit"> <property name="book. Service"> <ref bean="book. Service"/> </property> </beans> …

Spring integration with Hibernate v Two approaches § Inversion of Control with a Hibernate.

Spring integration with Hibernate v Two approaches § Inversion of Control with a Hibernate. Template and Callback. § Extending Hibernate. Dao. Support and Applying an AOP Interceptor. • Configure the Hibernate Session. Factory • Extend your DAO Implementation from Hibernate. Dao. Support • Wire in Transaction Support with AOP

Spring integration with Hibernate (Cont. ) v Configuring the Hibernate Session. Factory in Spring

Spring integration with Hibernate (Cont. ) v Configuring the Hibernate Session. Factory in Spring <bean id="session. Factory" class="org. springframework. orm. hibernate 3. Local. Ses sion. Factory. Bean"> <property name="mapping. Resources"> <list> <value>com/zabada/springrecipes/base/Widget. hbm. xml </value> </list> </property> </bean>

Spring integration with Hibernate (Cont. ) v Extending Hibernate. Dao. Support for the Actual

Spring integration with Hibernate (Cont. ) v Extending Hibernate. Dao. Support for the Actual DAO Implementation. public class Widget. DAOHibernate. Impl extends Hibernate. Dao. Support implements Widget. DAO { public Collection get. Widgets() { return get. Hibernate. Template(). load. All(Widget. class); } public Widget save. Widget(Widget widget) { get. Hibernate. Template(). save. Or. Update(widget); return widget; } }

Spring integration with Hibernate (Cont. ) v Using AOP to Wire Up the DAO

Spring integration with Hibernate (Cont. ) v Using AOP to Wire Up the DAO and Transaction Management <bean id="hibernate. Interceptor" class="org. springframework. orm. hibernate 3. Hibernate. In terceptor"> <property name="session. Factory"> <ref bean="session. Factory"/> </property> </bean> <bean id="widget. Dao. Target" class="com. zabada. springrecipes. hibernate. Widget. DAO Hibernate. Impl"> <property name="session. Factory"> <ref bean="session. Factory"/> </property></bean>

Spring integration with Hibernate (Cont. ) <bean id="widget. DAO" class="org. springframework. aop. framework. Proxy.

Spring integration with Hibernate (Cont. ) <bean id="widget. DAO" class="org. springframework. aop. framework. Proxy. Factor y. Bean"> <property name="proxy. Interfaces"> <value>com. zabada. springrecipes. base. Widget. DAO</v alue> </property> <property name="interceptor. Names"> <list> <value>hibernate. Interceptor</value> <value>widget. Dao. Target</value> </list> </property> </bean>

The Packaging for the Whole Project v Web. Root § WEB-INF • • •

The Packaging for the Whole Project v Web. Root § WEB-INF • • • Classes Config (application. Context. 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

Issues of System. out. println () v Output format for logging info isn’t so

Issues of System. out. println () v Output format for logging info isn’t so flexible. v Programmer has to recompile the source if there has some changes. v The efficiency of application can be decrease if there are so many println();

Logger’s Level v Off : The OFF Level has the highest possible rank and

Logger’s Level v Off : The OFF Level has the highest possible rank and is intended to turn off logging. v Fatal : The FATAL level designates very severe error events that will presumably lead the application to abort. v Error : The ERROR level designates error events that might still allow the application to continue running. v Warn : The WARN level designates potentially harmful situations. v Info : The INFO level designates informational messages that highlight the progress of the application at coarsegrained level. v Debug : The DEBUG Level designates fine-grained informational events that are most useful to debug an application. v All : The ALL Level has the lowest possible rank and is intended to turn on all logging.

Solutions for managing Log 4 j v User can enable, disable and switch the

Solutions for managing Log 4 j v 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.

Log 4 j. xml Configuration <? xml version="1. 0" encoding="UTF-8" ? > <!DOCTYPE log

Log 4 j. xml Configuration <? xml version="1. 0" encoding="UTF-8" ? > <!DOCTYPE log 4 j: configuration SYSTEM "log 4 j. dtd"> <log 4 j: configuration xmlns: log 4 j="http: //jakarta. apache. org/log 4 j/"> <appender name="CONSOLE" class="org. apache. log 4 j. Console. Appender"> <layout class="org. apache. log 4 j. Pattern. Layout"> <param name="Conversion. Pattern" 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> </log 4 j: configuration>

Log 4 j DEMO protected final Log logger = Log. Factory. get. Log(get. Class());

Log 4 j DEMO protected final Log logger = Log. Factory. get. Log(get. Class()); if (logger. is. Debug. Enabled()) { logger. debug("entering 'list' method. . . "); }

P 6 SPY v P 6 Log intercepts and logs the database statements of

P 6 SPY v P 6 Log intercepts and logs the database statements of any application that uses JDBC. v This application is particularly useful for developers to monitor the SQL statements produced by EJB servers Or ORM. v P 6 Spy is designed to be installed in minutes and requires no code changes.

Integrate P 6 SPY With Hibernate <bean id="data. Source" class="org. apache. commons. dbcp. Basic.

Integrate P 6 SPY With Hibernate <bean id="data. Source" class="org. apache. commons. dbcp. Basic. Data. Source"> <property name="driver. Class. Name"> <value>com. p 6 spy. engine. spy. P 6 Spy. Driver</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>

SQL Profiler DEMO

SQL Profiler DEMO

Reference v http: //www. java. com v http: //struts. apache. org/ v http: //sourceforge.

Reference v http: //www. java. com v http: //struts. apache. org/ v http: //sourceforge. net/ v http: //db. apache. org/ojb/ v http: //logging. apache. org/log 4 j/ v http: //jakarta. apache. org/velocity/ v http: //jakarta. apache. org/commons/ v http: //www. hibernate. org/ v http: //www. springframework. org/ v http: //www. p 6 spy. com/