Struts & Hibernate & Spring

 

Framework knows how to do and leave what to do to user with interface programming and dynamic configuration.html

What is Struts?java

  • Struts is a kind of MVC framework for developing web application, which has finished the flow of controller,knowing how to do when request come in,at same time left the what to do to developer.
  • Struts has seperated the presentation layer from the business logic layer.
  • Struts has a wide rang of JSP HTML tags, support resolution of DOM tags
  • Mainly used to build Web Application

Structs's process sequence for requestweb

  • Apache gets request from client
  • Transfer/Pass request to Struts framework
  • Struts framework selects a ActionServlet if there is a servlet mapping to request
  • Struts framework creates a form bean object related to Action and filled with request content
  • Struts will invoke the authentication method of FormBean object. Sometime like Smarty and template in PHP
  • If failing to authenticate, response to client to input again or redirect to other link
  • If the above process goes well, Struts call method execute() of Action
  • In execute() method, user code to resolve data or paremeters from FormBean Object and do some business logic.
  • Normally, Action call Session EJB to handle with business logic, such as insert, update, add, search some data.
  • After logic is finished, Action create or update a FormBean Objects with result for response
  • Action returns a Forward object to ActionServlet, and then is transfered to JSP.
  • JSP resolve the Formbean Object and generate HTML to respond.

 

Hibernate(Linq to SQL)spring

  • Get config file ready(hibernate.cfg.xml)
  • In config file all DB information are setting, including JDBC Driver, DB user, password.
  • SessionFactory create a session to connect to DB using config setting.
  • http://docs.jboss.org/hibernate/orm/4.2/quickstart/en-US/html_single/
  • Hibernate convert DB's tables and fields to its own class and class's propertis. Select will return a collection of objects
  • 對數據庫的寫操做包括保存、更新和刪除,當保存一個POJO持久對象時,觸發Hibernate的保存事件監聽器進行處理。Hibernate經過映射文件得到對象對應數據庫表名以及屬性所對應的表中的列名,而後經過反射機制持久化對象(實體對象)的各個屬性,最終組織成向數據庫插入新對象的SQLinsert語句。調用了session.save()方法後,這個對象會標識成持久化狀態存放在session中,對於Hibernate來講它就是一個持久化了的對象,但這個時候Hibernate還不會真正的執行insert語句,當進行session的刷新同部或事務提交時,Hibernate會把session緩存中的全部SQL語句一塊兒執行,對於更新、刪除操做也是採用相似的機制。
  • 而後,提交事務並事務提交成功後,這些寫操做就會被永久地保存進數據庫中,因此,使用session對數據庫操做還依賴於Hibernate事務的處理。若是設置了二級緩存,那麼這些操做會被同步到二級緩存中,Hibernate對數據庫最終操做也是依賴於底層JDBC對數據庫進行。
  • Hibernate如何從數據庫中載入對象.
  • 當使用session.load()載入對象時,能夠設置是否採用延遲加載,若是延遲加載,那麼load返回的對象實際是CGLIB或javassist返回的代理類,它的非主鍵屬性都是空的,這對於對象集合屬性頗有效。Hibernate以此來節約內存,當真正須要讀取對象時,Hibernate會先嚐試從session緩存中讀取,若是session緩存中數據不存在或者是髒數據而且配置了二級緩存,Hibernate嘗試從二級緩存中檢索數據,不然Hibernate會根據對象類型,主鍵等信息組織select語句到數據中讀取,再把select結果組織成對象返回
  • Hibernate如何進行數據庫查詢操做Hibernate提供SQLHQLCriteria查詢方式。HQL是其中運用最普遍的查詢方式。用戶使用session.createQuery()方法以一條HQL語句爲參數建立Query查詢對象後,Hibernate會使用Anltr庫把HQL語句解析成JDBC能夠識別的SQL語句,若是設置了查詢緩存,那麼執行Query.list()時,Hibernate會先對查詢緩存進行查詢,若是查詢緩存不存在,再使用select語句查詢數據庫。

Spring數據庫

  • Reference to:http://baike.baidu.com/view/23023.htm,  
  • http://www.springsource.org/
  • http://www.ibm.com/developerworks/web/library/wa-spring1/?S_TACT=105AGX52&S_CMP=cn-a-j
  • Spring provides an incredibly powerful and flexible collection of technologies to improve your enterprise Java application development that is used by millions of developers. It is easy to get started by using our free development tool, Spring Tool Suite, or following one of the many tutorials. If you have specific questions then you can ask them in the community forum, look for a solution in our extensive code samples or search the outstanding Spring documentation.
  • Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.緩存

    In this first article in my three-part Spring Series, I introduce you to the Spring framework. I start by describing the functionality of the framework in terms of its underlying modules and then discuss two of the most interesting modules, Spring aspect-oriented programming (AOP), and the Inversion of Control (IOC) container. I then use several examples to demonstrate the workings of the IOC container in a typical application use case scenario. The examples will also lay the foundation for an expanded discussion, later in this series, of the how the Spring framework implements AOP constructs through Spring AOP.session

  • Spring Structure

Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows:app

  • The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code.
  • Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
  • Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the Spring framework, through its configuration management feature. As a result you can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components.
  • Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy.
  • Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies.
  • Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects.
  • Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.

Spring framework functionality can be used in any J2EE server and most of it also is adaptable to non-managed environments. A central focus of Spring is to allow for reusable business and data-access objects that are not tied to specific J2EE services. Such objects can be reused across J2EE environments (Web or EJB), standalone applications, test environments, and so on, without any hassle.dom

Focus on:Interface-Oriented Programming & Inversion Of Control ( all concreate class is defined in spring application context.xml with object's property).ide

Take one example to understand how the spring application works.

Step1: We define our interfaces which the application will use. we will interface-oriented programming.

 1 public interface CreateCreditCardAccountInterface 
 2 {
 3     public CreditLinkingInterface getCreditLinkingInterface();
 4     public void setCreditLinkingInterface(CreditLinkingInterface creditLinkingInterface);
 5     public CreditRatingInterface getCreditRatingInterface();
 6     public void setCreditRatingInterface(CreditRatingInterface creditRatingInterface);
 7     public EmailInterface getEmailInterface();
 8     public void setEmailInterface(EmailInterface emailInterface);
 9     public void createCreditCardAccount(ICustomer icustomer) throws Exception;
10 }
View Code

In CreateCreditCardAccountInterface, we use Interface CreditLinkingInterface

1 public interface CreditLinkingInterface 
2 {    
3     public String getUrl();    
4     public void setUrl(String url);    
5     public void linkCreditBankAccount(ICustomer icustomer) throws Exception ;
6 }
View Code

In CreditLinkingInterface, we use interface ICustomer and CreditRatingInterface

 1 //Interface holds customer information.
 2 public interface ICustomer {
 3     public String getCustomerId();
 4     public void setCustomerId(String customerId);
 5     public String getFirstName();
 6     public void setFirstName(String firstName);
 7     public IAddress getIAddress();
 8     public void setIAddress(IAddress address);
 9     public String getLastName();
10     public void setLastName(String lastName);
11     public String getSsnId();
12     public void setSsnId(String ssnId);    
13     public String getEmailAddress();
14     public void setEmailAddress(String emailAddress);    
15     public boolean isCreditRating() ;
16     public void setCreditRating(boolean creditRating);
17 }
View Code
1 public interface CreditRatingInterface 
2 {
3    public boolean getUserCreditHistoryInformation(ICustomer iCustomer);
4 }
View Code

In ICustomer interface, we use interface  and IAddress

 1 public interface IAddress 
 2 {    
 3     public String getAddress1() ;    
 4     public void setAddress1(String address1) ;    
 5     public String getAddress2();    
 6     public void setAddress2(String address2);    
 7     public String getCity() ;    
 8     public void setCity(String city);    
 9     public String getCountry() ;    
10     public void setCountry(String country);    
11     public String getState();    
12     public void setState(String state) ;    
13     public String getZipCode() ;    
14     public void setZipCode(String zipCode) ;    
15 }
View Code

Step2: Now we shall config our application bean with our bussiness logic, these bean will create some concreate objects by Spring using Java Reflection.

 1 ?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
 3 <beans>    
 4     <bean id="createCreditCard" class="springexample.creditcardaccount.CreateCreditCardAccount">
 5         <property name="creditRatingInterface">
 6             <ref bean="creditRating" />
 7         </property>
 8         <property name="creditLinkingInterface">
 9             <ref bean="creditLinking" />
10         </property>
11         <property name="emailInterface">
12             <ref bean="email" />
13         </property>
14     </bean>    
15     <bean id="creditLinking" class="springexample.creditlinking.CreditLinking">
16         <property name="url">
17            <value>http://localhost/creditLinkService</value>
18         </property>
19     </bean>    
20     <bean id="creditRating" class="springexample.creditrating.CreditRating">
21         </bean>    
22     <bean id="email" class="springexample.email.Email">
23         <property name="smtpHost">
24             <value>localhost</value>
25         </property>
26         <property name="fromEmail">
27             <value>mycompanyadmin@mycompanyadmin.com</value>
28         </property>
29         <property name="userId">
30             <value>myuserid</value>
31         </property>
32         <property name="password">
33             <value>mypassword</value>
34         </property>
35     </bean>        
36 </beans>
View Code

Step3:OK, all is done, Application can run

  • We have main() function as application's entry

 

 1 package springexample.client;
 2 import org.springframework.context.support.ClassPathXmlApplicationContext;
 3 import springexample.creditcardaccount.CreateCreditCardAccountInterface;
 4 import springexample.domain.Customer;
 5 import springexample.domain.ICustomer;
 6 public class CreateCreditAccountClient 
 7 {    
 8     public static void main(String[] args)
 9         {
10       try
11       {
12         System.out.println("CreateCreditAccountClient started"); 
13             ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] {"springexample-creditaccount.xml"});    
14         System.out.println("Classpath loaded");    
15         ICustomer icustomer = new Customer();
16         icustomer.setCustomerId("1A2B3C");
17         icustomer.setEmailAddress("xxx@xx.com");
18         icustomer.setFirstName("xxx");
19         icustomer.setFirstName("yyy");
20     
21         CreateCreditCardAccountInterface creditCardAccount = (CreateCreditCardAccountInterface)
22         appContext.getBean("createCreditCard");    
23         creditCardAccount.createCreditCardAccount(icustomer);    
24         System.out.println("CreateCreditAccountClient end");
25      }
26      catch(Exception e)
27          {
28         e.printStackTrace();
29      }
30      }
31 }
View Code
  • In main function, we have concreate object Customer, now we need a concreate of CreateCreditCardAccountInterface which is given by object of ClassPathXmlApplicationContext via reading applicationcontext.xml
  • By reading applicationContext.xml, we acturally have a concreate object of CreateCreditCardAccountInterface like following code:
  •  1     CreateCreditCardAccountInterface creditCardAccount = (CreateCreditCardAccountInterface)
     2     
     3     appContext.getBean("createCreditCard"); //This line code acturally can be converted to following code.  4     
     5     //email = Class.forName("springexample.email.Email");
     6     //emial.setSmtpHost("localhost");
     7     //emial.setFromEmail("mycompanyadmin@mycompanyadmin.com");
     8     //emial.setPassword("myuserid");
     9     //emial.setUserId("mypassword");
    10     
    11     //creditRating = Class.forName("springexample.creditrating.CreditRating");
    12     //creditLinking = Class.forName("springexample.creditlinking.CreditLinking");
    13     //creditLinking.setUrl("http://localhost/creditLinkService");    
    14             
    15     //creditCardAccount = Class.forName("springexample.creditcardaccount.CreateCreditCardAccount");
    16     //creditCardAccount.setCreditLinkingInterface(creditLinking);
    17     //creditCardAccount.setCreditRatingInterface(creditLinking);
    18     //creditCardAccount.setEmailInterface(creditLinking);    
    19     
    20     creditCardAccount.createCreditCardAccount(icustomer);
  • Till now,all concreate objects is created and application can run correctly.
  • Spring' XML: 
    • bean <===> concreate object;
    • <bean id=> define the name of concreate name;
    • <property name="creditRatingInterface"> is mapped to set method "setCreditRatingInterface" with parameter <ref bean="creditLinking" />  where ref means a reference object created as bean. Same as setter and getter methods in C#
    • <value>localhost</value> where value means in-built type with value.
相關文章
相關標籤/搜索