1 / 59

Java 2 Enterprise Edition SSH Frameworks

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

eliasa
Download Presentation

Java 2 Enterprise Edition SSH Frameworks

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java 2 Enterprise EditionSSH Frameworks Presenter : Lee, Gun 2007-02-05 Updated

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

  3. Process for running JSP JSP File Request Web Browser Servlet Source Code Response Compiled Servlet Class

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

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

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

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

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

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

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

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

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

  13. 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; } }

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

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

  16. 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"); } }

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

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

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

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

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

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

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

  24. Hibernate Architecture Transient Objects Business Layer Persistence Objects Persistence Layer Session Factory Session Transaction Transaction Factory Connection Provider JNDI JDBC JTA Hibernate API J2EE API

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

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

  27. 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; } }

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

  29. 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); }

  30. 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; } }

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

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

  33. Summery 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

  34. What is IoC? • IoC is short of Inversion of Control. Interface Finder Lister finder finderByID listByID <implements> FinderWithConstruct <<create>> listObjectName FinderWithConstruct finderByID private Finder finder = new FinderWithConstruct();

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

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

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

  38. SSH Framework - Struts Struts-config.xml Spring 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

  39. SSH Framework - Spring Struts Hibernate Action (Business Logic) ServiceImpl Web Browser Action Form (Java Bean Or EJB) AbstractService Other Action ApplicationContext.xml S S H

  40. SSH Framework - Hibernate Struts Spring DAOImpl ModelImpl Web Browser AbstractDAO AbstractModel XXX.hbm.xml S S H

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

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

  43. 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> …

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

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

  46. Spring 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.class); } public Widget saveWidget(Widget widget) { getHibernateTemplate().saveOrUpdate(widget); return widget; } }

  47. Spring integration with Hibernate (Cont.) • Using AOP to Wire Up the DAO and Transaction Management <bean id="hibernateInterceptor" class="org.springframework.orm.hibernate3.HibernateInterceptor"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="widgetDaoTarget" class="com.zabada.springrecipes.hibernate.WidgetDAOHibernateImpl"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property></bean>

  48. Spring integration with Hibernate (Cont.) <bean id="widgetDAO" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>com.zabada.springrecipes.base.WidgetDAO</value> </property> <property name="interceptorNames"> <list> <value>hibernateInterceptor</value> <value>widgetDaoTarget</value> </list> </property> </bean>

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

  50. Issues ofSystem.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();

More Related