seasun  
          在不斷模仿、思考、總結中一步一步進步!
          公告
          •     我的blog中的部分資源是來自于網絡上,如果您認為侵犯了您的權利,請及時聯系我,我會盡快刪除!E-MAIL:shiwenfeng@aliyun.com和QQ:281340916,歡迎交流。

          日歷
          <2025年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          導航

          常用鏈接

          隨筆分類

          good blog author

          積分與排名

          • 積分 - 81738
          • 排名 - 700

          最新評論

          閱讀排行榜

           

          2010年1月25日

          一、首先,模塊的組織更加的細致,從那么多的jar分包就看的出來:

           

          Spring的構建系統以及依賴管理使用的是Apache Ivy,從源碼包看出,也使用了Maven。

          Maven確實是個好東西,好處不再多言,以后希望能進一步用好它。

          二、新特性如下:

          Spring Expression Language (Spring表達式語言)

          IoC enhancements/Java based bean metadata (Ioc增強/基于Java的bean元數據)

          General-purpose type conversion system and UI field formatting system (通用類型轉換系統和UI字段格式化系統)

          Object to XML mapping functionality (OXM) moved from Spring Web Services project (對象到XML映射功能從Spring Web Services項目移出)

          Comprehensive REST support (廣泛的REST支持)

          @MVC additions (@MVC增強)

          Declarative model validation (聲明式模型驗證)

          Early support for Java EE 6 (提前對Java EE6提供支持)

          Embedded database support (嵌入式數據庫的支持)

          三、針對Java 5的核心API升級

          1、BeanFactory接口盡可能返回明確的bean實例,例如:

          T getBean(String name, Class requiredType)

          Map getBeansOfType(Class type)

          Spring3對泛型的支持,又進了一步。個人建議泛型應該多用,有百利而無一害!

          2、Spring的TaskExecutor接口現在繼承自java.util.concurrent.Executor:

          擴展的子接口AsyncTaskExecutor支持標準的具有返回結果Futures的Callables。

          任務計劃,個人還是更喜歡Quartz。

          3、新的基于Java5的API和SPI轉換器

          無狀態的ConversionService 和 Converters

          取代標準的JDK PropertyEditors

          類型化的ApplicationListener,這是一個實現“觀察者設計模式”使用的事件監聽器。

          基于事件的編程模式,好處多多,在項目中應該考慮使用,基于事件、狀態遷移的設計思路,有助于理清軟件流程,和減少項目的耦合度。

          四、Spring表達式語言

          Spring表達式語言是一種從語法上和統一表達式語言(Unified EL)相類似的語言,但提供更多的重要功能。它可以在基于XML配置文件和基于注解的bean配置中使用,并作為基礎為跨Spring portfolio平臺使用表達式語言提供支持。

          接下來,是一個表達式語言如何用于配置一個數據庫安裝中的屬性的示例:

          <bean class="mycompany.RewardsTestDatabase">
              <property name="databaseName"
                  value="#{systemProperties.databaseName}"/>
              <property name="keyGenerator"
                  value="#{strategyBean.databaseKeyGenerator}"/>
          </bean>
          如果你更愿意使用注解來配置你的組件,那么這種功能同樣可用:

          @Repository public class RewardsTestDatabase {
                @Value("#{systemProperties.databaseName}")
                public void setDatabaseName(String dbName) { … }
               
                @Value("#{strategyBean.databaseKeyGenerator}")
                public voidsetKeyGenerator(KeyGenerator kg) { … }
          }

          又多一種表達式語言,造輪子的運動還在繼續中!

          五、基于Java的bean元數據

          JavaConfig項目中的一些核心特性已經集成到了Spring中來,這意味著如下這些特性現在已經可用了:

          @Configuration

          @Bean

          @DependsOn

          @Primary

          @Lazy

          @Import

          @Value

          又來一堆的注解,無語了,感覺還是配置文件方便!:(

          這兒有一個例子,關于一個Java類如何使用新的JavaConfig特性提供基礎的配置信息:

          package org.example.config;

          @Configuration
          public class AppConfig {
              private @Value("#{jdbcProperties.url}") String jdbcUrl;
              private @Value("#{jdbcProperties.username}") String username;
              private @Value("#{jdbcProperties.password}") String password;

              @Bean
              public FooService fooService() {
                  return new FooServiceImpl(fooRepository());
              }

              @Bean
              public FooRepository fooRepository() {
                  return new HibernateFooRepository(sessionFactory());
              }

              @Bean
              public SessionFactory sessionFactory() {
                  // wire up a session factory
                  AnnotationSessionFactoryBean asFactoryBean =
                      new AnnotationSessionFactoryBean();
                  asFactoryBean.setDataSource(dataSource());
                  // additional config
                  return asFactoryBean.getObject();
              }

              @Bean
              public DataSource dataSource() {
                  return new DriverManagerDataSource(jdbcUrl, username, password);
              }
          }為了讓這段代碼開始生效,我們需要添加如下組件掃描入口到最小化的應用程序上下文配置文件中:

          <context:component-scan base-package="org.example.config"/>
          <util:properties id="jdbcProperties" location="classpath:org/example/config/jdbc.properties"/>

          六、在組件中定義bean的元數據

          感覺Spring提供了越來越多的注解、元數據,復雜性已經超出了當初帶來的方便本身!

          七、通用類型轉換系統和UI字段格式化系統

          Spring3加入了一個通用的類型轉換系統,目前它被SpEL用作類型轉換,并且可能被一個Spring容器使用,用于當綁定bean的屬性值的時候進行類型轉換。

          另外,還增加了一個UI字段格式化系統,它提供了更簡單的使用并且更強大的功能以替代UI環境下的JavaBean的PropertyEditors,例如在SpringMVC中。

          這個特性要好好研究下,通用類型轉換系統如果果如所言的話,帶來的好處還是很多的。

          八、數據層

          對象到XML的映射功能已經從Spring Web Services項目移到了Spring框架核心中。它位于org.springframework.oxm包中。

          OXM?研究下!時間真不夠!

          九、Web層

          在Web層最激動人心的新特性莫過于新增的對構件REST風格的web服務和web應用的支持!另外,還新增加了一些任何web應用都可以使用的新的注解。

          服務端對于REST風格的支持,是通過擴展既有的注解驅動的MVC web框架實現的。

          客戶端的支持則是RestTemplate類提供的。

          無論服務端還是客戶端REST功能,都是使用HttpConverter來簡化對HTTP請求和應答過程中的對象到表現層的轉換過程。

          MarshallingHttpMessageConverter使用了上面提到的“對象到XML的映射機制”。

          十、@MVC增強

          新增了諸如@CookieValue 和 @RequestHeaders這樣的注解等。

          十一、聲明式模型驗證

          支持JSR 303,使用Hibernate Validator作為實現。

          十二、提前對Java EE6提供支持

          提供了使用@Async注解對于異步方法調用的支持(或者EJB 3.1里的 @Asynchronous)

          另外,新增對JSR 303, JSF 2.0, JPA 2.0等的支持。

          十三、嵌入式數據庫的支持

          對于嵌入式的Java數據庫引擎提供了廣泛而方便的支持,諸如HSQL, H2, 以及Derby等。

          這是不是代表一種潮流呢?數據庫向越來越小型化發展,甚至小型化到嵌入式了,我認為這在桌面級應用上還是很有市場的。

           

          本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/abigfrog/archive/2009/10/30/4748685.aspx

          posted @ 2010-01-25 17:26 shiwf 閱讀(4710) | 評論 (0)編輯 收藏

          2010年1月24日

          請查看此blog: http://conkeyn.javaeye.com/category/35770

          HQL: Hibernate查詢語言

          Hibernate配備了一種非常強大的查詢語言,這種語言看上去很像SQL。但是不要被語法結構上的相似所迷惑,HQL是非常有意識的被設計為完全面向對象的查詢,它可以理解如繼承、多態 和關聯之類的概念。

          1.大小寫敏感性問題

          除了Java類與屬性的名稱外,查詢語句對大小寫并不敏感。 所以 SeLeCT sELEct 以及 SELECT 是相同的,但是 org.hibernate.eg.FOO 并不等價于 org.hibernate.eg.Foo 并且 foo.barSet 也不等價于 foo.BARSET 。

          本手冊中的HQL關鍵字將使用小寫字母. 很多用戶發現使用完全大寫的關鍵字會使查詢語句 的可讀性更強, 但我們發現,當把查詢語句嵌入到Java語句中的時候使用大寫關鍵字比較難看。

          2.from子句

          Hibernate中最簡單的查詢語句的形式如下:

          from eg.Cat
          
          

          該子句簡單的返回eg.Cat 類的所有實例。通常我們不需要使用類的全限定名, 因為 auto-import (自動引入) 是缺省的情況。所以我們幾乎只使用如下的簡單寫法:

          from Cat
          
          

          大多數情況下, 你需要指定一個別名 , 原因是你可能需要 在查詢語句的其它部分引用到Cat

          from Cat as cat
          
          

          這個語句把別名cat 指定給類Cat 的實例, 這樣我們就可以在隨后的查詢中使用此別名了。關鍵字as 是可選的,我們也可以這樣寫:

          from Cat cat
          
          

          子句中可以同時出現多個類, 其查詢結果是產生一個笛卡兒積或產生跨表的連接。

          from Formula, Parameter
          
          
          from Formula as form, Parameter as param
          
          

          查詢語句中別名的開頭部分小寫被認為是實踐中的好習慣, 這樣做與Java變量的命名標準保持了一致 (比如,domesticCat )。

          3.關聯(Association)與連接(Join)

          我們也可以為相關聯的實體甚至是對一個集合中的全部元素指定一個別名, 這時要使用關鍵字join 。

          from Cat as cat
          inner join cat.mate as mate
          left outer join cat.kittens as kitten
          
          
          from Cat as cat left join cat.mate.kittens as kittens
          
          
          from Formula form full join form.parameter param
          
          

          受支持的連接類型是從ANSI SQL中借鑒來的。

          • inner join (內連接)

          • left outer join (左外連接)

          • right outer join (右外連接)

          • full join (全連接,并不常用)

          語句inner join , left outer join 以及 right outer join 可以簡寫。

          from Cat as cat
          join cat.mate as mate
          left join cat.kittens as kitten
          
          

          還有,一個"fetch"連接允許僅僅使用一個選擇語句就將相關聯的對象或一組值的集合隨著他們的父對象的初始化而被初始化,這種方法在使用到集合的情況下尤其有用,對于關聯和集合來說,它有效的代替了映射文件中的外聯接與延遲聲明(lazy declarations). 查看 第20.1節 “ 抓取策略(Fetching strategies) ” 以獲得等多的信息。

          from Cat as cat
          inner join fetch cat.mate
          left join fetch cat.kittens
          
          

          一個fetch連接通常不需要被指定別名, 因為相關聯的對象不應當被用在 where 子句 (或其它任何子句)中。同時,相關聯的對象并不在查詢的結果中直接返回,但可以通過他們的父對象來訪問到他們。

          注意fetch 構造變量在使用了scroll() iterate() 函數的查詢中是不能使用的。最后注意,使用full join fetch right join fetch 是沒有意義的。

          如果你使用屬性級別的延遲獲取(lazy fetching)(這是通過重新編寫字節碼實現的),可以使用 fetch all properties 來強制Hibernate立即取得那些原本需要延遲加載的屬性(在第一個查詢中)。

          from Document fetch all properties order by name
          
          
          from Document doc fetch all properties where lower(doc.name) like '%cats%'
          
          

          4.select子句

          select 子句選擇將哪些對象與屬性返回到查詢結果集中. 考慮如下情況:

          select mate
          from Cat as cat
          inner join cat.mate as mate
          
          

          該語句將選擇mate s of other Cat s。(其他貓的配偶) 實際上, 你可以更簡潔的用以下的查詢語句表達相同的含義:

          select cat.mate from Cat cat
          
          

          查詢語句可以返回值為任何類型的屬性,包括返回類型為某種組件(Component)的屬性:

          select cat.name from DomesticCat cat
          where cat.name like 'fri%'
          
          
          select cust.name.firstName from Customer as cust
          
          

          查詢語句可以返回多個對象和(或)屬性,存放在 Object[] 隊列中,

          select mother, offspr, mate.name
          from DomesticCat as mother
          inner join mother.mate as mate
          left outer join mother.kittens as offspr
          
          

          或存放在一個List 對象中,

          select new list(mother, offspr, mate.name)
          from DomesticCat as mother
          inner join mother.mate as mate
          left outer join mother.kittens as offspr
          
          

          也可能直接返回一個實際的類型安全的Java對象,

          select new Family(mother, mate, offspr)
          from DomesticCat as mother
          join mother.mate as mate
          left join mother.kittens as offspr
          
          

          假設類Family 有一個合適的構造函數.

          你可以使用關鍵字as 給“被選擇了的表達式”指派別名:

          select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n
          from Cat cat
          
          

          這種做法在與子句select new map 一起使用時最有用:

          select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
          from Cat cat
          
          

          該查詢返回了一個Map 的對象,內容是別名與被選擇的值組成的名-值映射。

          5.聚集函數

          HQL查詢甚至可以返回作用于屬性之上的聚集函數的計算結果:

          select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)
          from Cat cat
          
          

          受支持的聚集函數如下:

          • avg(...), sum(...), min(...), max(...)

          • count(*)

          • count(...), count(distinct ...), count(all...)

          你可以在選擇子句中使用數學操作符、連接以及經過驗證的SQL函數:

          select cat.weight + sum(kitten.weight)
          from Cat cat
          join cat.kittens kitten
          group by cat.id, cat.weight
          
          
          select firstName||' '||initial||' '||upper(lastName) from Person
          
          

          關鍵字distinct all 也可以使用,它們具有與SQL相同的語義.

          select distinct cat.name from Cat cat
          select count(distinct cat.name), count(cat) from Cat cat
          
          

          6.多態查詢

          一個如下的查詢語句:

          from Cat as cat
          
          

          不僅返回Cat 類的實例, 也同時返回子類 DomesticCat 的實例. Hibernate 可以在from 子句中指定任何 Java 類或接口. 查詢會返回繼承了該類的所有持久化子類的實例或返回聲明了該接口的所有持久化類的實例。下面的查詢語句返回所有的被持久化的對象:

          from java.lang.Object o
          
          

          接口Named 可能被各種各樣的持久化類聲明:

          from Named n, Named m where n.name = m.name
          
          

          注意,最后的兩個查詢將需要超過一個的SQL SELECT .這表明order by 子句 沒有對整個結果集進行正確的排序. (這也說明你不能對這樣的查詢使用Query.scroll() 方法.)

          7.where子句

          where 子句允許你將返回的實例列表的范圍縮小. 如果沒有指定別名,你可以使用屬性名來直接引用屬性:

          from Cat where name='Fritz'
          
          

          如果指派了別名,需要使用完整的屬性名:

          from Cat as cat where cat.name='Fritz'
          
          

          返回名為(屬性name等于)'Fritz'的Cat 類的實例。

          select foo
          from Foo foo, Bar bar
          where foo.startDate = bar.date
          
          

          將返回所有滿足下面條件的Foo 類的實例:存在如下的bar 的一個實例,其date 屬性等于 Foo startDate 屬性。 復合路徑表達式使得where 子句非常的強大,考慮如下情況:

          from Cat cat where cat.mate.name is not null
          
          

          該查詢將被翻譯成為一個含有表連接(內連接)的SQL查詢。如果你打算寫像這樣的查詢語句

          from Foo foo
          where foo.bar.baz.customer.address.city is not null
          
          

          在SQL中,你為達此目的將需要進行一個四表連接的查詢。

          = 運算符不僅可以被用來比較屬性的值,也可以用來比較實例:

          from Cat cat, Cat rival where cat.mate = rival.mate
          
          
          select cat, mate
          from Cat cat, Cat mate
          where cat.mate = mate
          
          

          特殊屬性(小寫)id 可以用來表示一個對象的唯一的標識符。(你也可以使用該對象的屬性名。)

          from Cat as cat where cat.id = 123
          from Cat as cat where cat.mate.id = 69
          
          

          第二個查詢是有效的。此時不需要進行表連接!

          同樣也可以使用復合標識符。比如Person 類有一個復合標識符,它由country 屬性 與medicareNumber 屬性組成。

          from bank.Person person
          where person.id.country = 'AU'
          and person.id.medicareNumber = 123456
          
          
          from bank.Account account
          where account.owner.id.country = 'AU'
          and account.owner.id.medicareNumber = 123456
          
          

          第二個查詢也不需要進行表連接。

          同樣的,特殊屬性class 在進行多態持久化的情況下被用來存取一個實例的鑒別值(discriminator value)。 一個嵌入到where子句中的Java類的名字將被轉換為該類的鑒別值。

          from Cat cat where cat.class = DomesticCat
          
          

          你也可以聲明一個屬性的類型是組件或者復合用戶類型(以及由組件構成的組件等等)。永遠不要嘗試使用以組件類型來結尾的路徑表達式(path-expression_r)(與此相反,你應當使用組件的一個屬性來結尾)。 舉例來說,如果store.owner 含有一個包含了組件的實體address

          store.owner.address.city    // 正確
          store.owner.address         // 錯誤!
          
          

          一個“任意”類型有兩個特殊的屬性id class , 來允許我們按照下面的方式表達一個連接(AuditLog.item 是一個屬性,該屬性被映射為<any> )。

          from AuditLog log, Payment payment
          where log.item.class = 'Payment' and log.item.id = payment.id
          
          

          注意,在上面的查詢與句中,log.item.class payment.class 將涉及到完全不同的數據庫中的列。

          8.表達式

          where 子句中允許使用的表達式包括大多數你可以在SQL使用的表達式種類:

          • 數學運算符+, -, *, /

          • 二進制比較運算符=, >=, <=, <>, !=, like

          • 邏輯運算符and, or, not

          • in , not in , between , is null , is not null , is empty , is not empty , member of and not member of

          • "簡單的" case, case ... when ... then ... else ... end ,和 "搜索" case, case when ... then ... else ... end

          • 字符串連接符...||... or concat(...,...)

          • current_date() , current_time() , current_timestamp()

          • second(...) , minute(...) , hour(...) , day(...) , month(...) , year(...) ,

          • EJB-QL 3.0定義的任何函數或操作:substring(), trim(), lower(), upper(), length(), locate(), abs(), sqrt(), bit_length()

          • coalesce() nullif()

          • cast(... as ...) , 其第二個參數是某Hibernate類型的名字,以及extract(... from ...) ,只要ANSI cast() extract() 被底層數據庫支持

          • 任何數據庫支持的SQL標量函數,比如sign() , trunc() , rtrim() , sin()

          • JDBC參數傳入 ?

          • 命名參數:name , :start_date , :x1

          • SQL 直接常量 'foo' , 69 , '1970-01-01 10:00:01.0'

          • Java public static final 類型的常量 eg.Color.TABBY

          關鍵字in between 可按如下方法使用:

          from DomesticCat cat where cat.name between 'A' and 'B'
          
          
          from DomesticCat cat where cat.name in ( 'Foo', 'Bar', 'Baz' )
          
          

          而且否定的格式也可以如下書寫:

          from DomesticCat cat where cat.name not between 'A' and 'B'
          
          
          from DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' )
          
          

          同樣, 子句is null is not null 可以被用來測試空值(null).

          在Hibernate配置文件中聲明HQL“查詢替代(query substitutions)”之后,布爾表達式(Booleans)可以在其他表達式中輕松的使用:

          <property name="hibernate.query.substitutions">true 1, false 0</property>
          
          

          系統將該HQL轉換為SQL語句時,該設置表明將用字符 1 0 來 取代關鍵字true false :

          from Cat cat where cat.alive = true
          
          

          你可以用特殊屬性size , 或是特殊函數size() 測試一個集合的大小。

          from Cat cat where cat.kittens.size > 0
          
          
          from Cat cat where size(cat.kittens) > 0
          
          

          對于索引了(有序)的集合,你可以使用minindex maxindex 函數來引用到最小與最大的索引序數。同理,你可以使用minelement maxelement 函數來引用到一個基本數據類型的集合中最小與最大的元素。

          from Calendar cal where maxelement(cal.holidays) > current date
          
          
          from Order order where maxindex(order.items) > 100
          
          
          from Order order where minelement(order.items) > 10000
          
          

          在傳遞一個集合的索引集或者是元素集(elements indices 函數) 或者傳遞一個子查詢的結果的時候,可以使用SQL函數any, some, all, exists, in

          select mother from Cat as mother, Cat as kit
          where kit in elements(foo.kittens)
          
          
          select p from NameList list, Person p
          where p.name = some elements(list.names)
          
          
          from Cat cat where exists elements(cat.kittens)
          
          
          from Player p where 3 > all elements(p.scores)
          
          
          from Show show where 'fizard' in indices(show.acts)
          
          

          注意,在Hibernate3種,這些結構變量- size , elements , indices , minindex , maxindex , minelement , maxelement - 只能在where子句中使用。

          一個被索引過的(有序的)集合的元素(arrays, lists, maps)可以在其他索引中被引用(只能在where子句中):

          from Order order where order.items[0].id = 1234
          
          
          select person from Person person, Calendar calendar
          where calendar.holidays['national day'] = person.birthDay
          and person.nationality.calendar = calendar
          
          
          select item from Item item, Order order
          where order.items[ order.deliveredItemIndices[0] ] = item and order.id = 11
          
          
          select item from Item item, Order order
          where order.items[ maxindex(order.items) ] = item and order.id = 11
          
          

          [] 中的表達式甚至可以是一個算數表達式。

          select item from Item item, Order order
          where order.items[ size(order.items) - 1 ] = item
          
          

          對于一個一對多的關聯(one-to-many association)或是值的集合中的元素, HQL也提供內建的index() 函數,

          select item, index(item) from Order order
          join order.items item
          where index(item) < 5
          
          

          如果底層數據庫支持標量的SQL函數,它們也可以被使用

          from DomesticCat cat where upper(cat.name) like 'FRI%'
          
          

          如果你還不能對所有的這些深信不疑,想想下面的查詢。如果使用SQL,語句長度會增長多少,可讀性會下降多少:

          select cust
          from Product prod,
          Store store
          inner join store.customers cust
          where prod.name = 'widget'
          and store.location.name in ( 'Melbourne', 'Sydney' )
          and prod = all elements(cust.currentOrder.lineItems)
          
          

          提示: 會像如下的語句

          SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order
          FROM customers cust,
          stores store,
          locations loc,
          store_customers sc,
          product prod
          WHERE prod.name = 'widget'
          AND store.loc_id = loc.id
          AND loc.name IN ( 'Melbourne', 'Sydney' )
          AND sc.store_id = store.id
          AND sc.cust_id = cust.id
          AND prod.id = ALL(
          SELECT item.prod_id
          FROM line_items item, orders o
          WHERE item.order_id = o.id
          AND cust.current_order = o.id
          )
          
          

          9.order by子句

          查詢返回的列表(list)可以按照一個返回的類或組件(components)中的任何屬性(property)進行排序:

          from DomesticCat cat
          order by cat.name asc, cat.weight desc, cat.birthdate
          
          

          可選的asc desc 關鍵字指明了按照升序或降序進行排序.

          10.group by子句

          一個返回聚集值(aggregate values)的查詢可以按照一個返回的類或組件(components)中的任何屬性(property)進行分組:

          select cat.color, sum(cat.weight), count(cat)
          from Cat cat
          group by cat.color
          
          
          select foo.id, avg(name), max(name)
          from Foo foo join foo.names name
          group by foo.id
          
          

          having 子句在這里也允許使用.

          select cat.color, sum(cat.weight), count(cat)
          from Cat cat
          group by cat.color
          having cat.color in (eg.Color.TABBY, eg.Color.BLACK)
          
          

          如果底層的數據庫支持的話(例如不能在MySQL中使用),SQL的一般函數與聚集函數也可以出現 在having order by 子句中。

          select cat
          from Cat cat
          join cat.kittens kitten
          group by cat
          having avg(kitten.weight) > 100
          order by count(kitten) asc, sum(kitten.weight) desc
          
          

          注意group by 子句與 order by 子句中都不能包含算術表達式(arithmetic expression_rs).

          posted @ 2010-01-24 13:55 shiwf 閱讀(2074) | 評論 (0)編輯 收藏
           

          DWR 3.0 上傳文件

          第一步:需要文件包,其實就是dwr 3.0中例子所需要的包, dwr.jar 、 commons-fileupload-1.2.jar 、 commons-io-1.3.1.jar 。

           

           

           

          第二步:編輯web.xml,添加dwr-invoke

          Xml代碼 復制代碼
          1. <servlet>  
          2.     <display-name>DWR Sevlet</display-name>  
          3.     <servlet-name>dwr-invoker</servlet-name>  
          4.     <servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>  
          5.     <init-param>  
          6.         <description>是否打開調試功能</description>  
          7.         <param-name>debug</param-name>  
          8.         <param-value>true</param-value>  
          9.     </init-param>  
          10.     <init-param>  
          11.         <description>日志級別有效值為: FATAL, ERROR, WARN (the default), INFO and DEBUG.</description>  
          12.         <param-name>logLevel</param-name>  
          13.         <param-value>DEBUG</param-value>  
          14.     </init-param>  
          15.     <init-param>  
          16.         <description>是否激活反向Ajax</description>  
          17.         <param-name>activeReverseAjaxEnabled</param-name>  
          18.         <param-value>true</param-value>  
          19.     </init-param>  
          20.     <init-param>     
          21.          <description>在WEB啟動時是否創建范圍為application的creator</description>     
          22.          <param-name>initApplicationScopeCreatorsAtStartup</param-name>     
          23.          <param-value>true</param-value>     
          24.     </init-param>     
          25.     <init-param>  
          26.         <description>在WEB啟動時是否創建范圍為application的creator</description>     
          27.         <param-name>preferDataUrlSchema</param-name>  
          28.         <param-value>false</param-value>  
          29.     </init-param>  
          30.         <load-on-startup>1</load-on-startup>     
          31.        
          32. </servlet>  
          33. <servlet-mapping>  
          34.     <servlet-name>dwr-invoker</servlet-name>  
          35.     <url-pattern>/dwr/*</url-pattern>  
          36. </servlet-mapping>  

           第三步:創建上傳類FileUpload.java,編輯代碼,內容如下:

          Java代碼 復制代碼
          1. package learn.dwr.upload_download;   
          2.   
          3. import java.awt.Color;   
          4. import java.awt.Font;   
          5. import java.awt.Graphics2D;   
          6. import java.awt.geom.AffineTransform;   
          7. import java.awt.image.AffineTransformOp;   
          8. import java.awt.image.BufferedImage;   
          9. import java.io.File;   
          10. import java.io.FileOutputStream;   
          11. import java.io.InputStream;   
          12. import org.directwebremoting.WebContext;   
          13. import org.directwebremoting.WebContextFactory;   
          14.   
          15. /**  
          16.  * title: 文件上傳  
          17.  * @author Administrator  
          18.  * @時間 2009-11-22:上午11:40:22  
          19.  */  
          20. public class FileUpload {   
          21.   
          22.     /**  
          23.      * @param uploadImage 圖片文件流  
          24.      * @param uploadFile 需要用簡單的文本文件,如:.txt文件,不然上傳會出亂碼  
          25.      * @param color  
          26.      * @return  
          27.      */  
          28.     public BufferedImage uploadFiles(BufferedImage uploadImage,   
          29.             String uploadFile, String color) {   
          30.         // uploadImage = scaleToSize(uploadImage);   
          31.         // uploadImage =grafitiTextOnImage(uploadImage, uploadFile, color);   
          32.         return uploadImage;   
          33.     }   
          34.   
          35.     /**  
          36.      * 文件上傳時使用InputStream類進行接收,在DWR官方例中是使用String類接收簡單內容  
          37.      *   
          38.      * @param uploadFile  
          39.      * @return  
          40.      */  
          41.     public String uploadFile(InputStream uploadFile, String filename)   
          42.             throws Exception {   
          43.         WebContext webContext = WebContextFactory.get();   
          44.         String realtivepath = webContext.getContextPath() + "/upload/";   
          45.         String saveurl = webContext.getHttpServletRequest().getSession()   
          46.                 .getServletContext().getRealPath("/upload");   
          47.         File file = new File(saveurl + "/" + filename);   
          48.         // if (!file.exists()) {   
          49.         // file.mkdirs();   
          50.         // }   
          51.         int available = uploadFile.available();   
          52.         byte[] b = new byte[available];   
          53.         FileOutputStream foutput = new FileOutputStream(file);   
          54.         uploadFile.read(b);   
          55.         foutput.write(b);   
          56.         foutput.flush();   
          57.         foutput.close();   
          58.         uploadFile.close();   
          59.         return realtivepath + filename;   
          60.     }   
          61.   
          62.     private BufferedImage scaleToSize(BufferedImage uploadImage) {   
          63.         AffineTransform atx = new AffineTransform();   
          64.         atx   
          65.                 .scale(200d / uploadImage.getWidth(), 200d / uploadImage   
          66.                         .getHeight());   
          67.         AffineTransformOp atfOp = new AffineTransformOp(atx,   
          68.                 AffineTransformOp.TYPE_BILINEAR);   
          69.         uploadImage = atfOp.filter(uploadImage, null);   
          70.         return uploadImage;   
          71.     }   
          72.   
          73.     private BufferedImage grafitiTextOnImage(BufferedImage uploadImage,   
          74.             String uploadFile, String color) {   
          75.         if (uploadFile.length() < 200) {   
          76.             uploadFile += uploadFile + " ";   
          77.         }   
          78.         Graphics2D g2d = uploadImage.createGraphics();   
          79.         for (int row = 0; row < 10; row++) {   
          80.             String output = "";   
          81.             if (uploadFile.length() > (row + 1) * 20) {   
          82.                 output += uploadFile.substring(row * 20, (row + 1) * 20);   
          83.             } else {   
          84.                 output = uploadFile.substring(row * 20);   
          85.             }   
          86.             g2d.setFont(new Font("SansSerif", Font.BOLD, 16));   
          87.             g2d.setColor(Color.blue);   
          88.             g2d.drawString(output, 5, (row + 1) * 20);   
          89.         }   
          90.         return uploadImage;   
          91.     }   
          92. }  

           第四步:添加到dwr.xml

          Java代碼 復制代碼
          1. <create creator="new">   
          2.     <param name="class" value="learn.dwr.upload_download.FileUpload" />   
          3. </create>  

           第五步:添加前臺html代碼

          Html代碼 復制代碼
          1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
          2. <html xmlns="http://www.w3.org/1999/xhtml">  
          3. <head>  
          4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
          5. <title>二進制文件處理,文件上傳</title>  
          6. <script type='text/javascript' src='/learnajax/dwr/interface/FileUpload.js'></script>  
          7. <script type='text/javascript' src='/learnajax/dwr/engine.js'></script>  
          8. <script type='text/javascript' src='/learnajax/dwr/util.js'></script>  
          9. <script type='text/javascript' >  
          10. function uploadFiles(){   
          11.     var uploadImage = dwr.util.getValue("uploadImage");   
          12.      FileUpload.uploadFiles(uploadImage, "", "", function(imageURL) {   
          13.         alert(imageURL);   
          14.         dwr.util.setValue('image', imageURL);   
          15.   });   
          16.   
          17. }   
          18. function uploadFile(){   
          19.     var uploadFile = dwr.util.getValue("uploadFile");   
          20.     //var uploadFile =document.getElementById("uploadFile").value;   
          21.     var uploadFileuploadFile_temp = uploadFile.value.replace("\\","/");   
          22.     var filenames = uploadFile.value.split("/");   
          23.     var filename = filenames[filenames.length-1];   
          24.     //var eextension = e[e.length-1];   
          25.     FileUpload.uploadFile(uploadFile,filename,function(data){   
          26.         var file_adocument.getElementById("file_a");   
          27.         file_a.href=data;   
          28.         file_a.innerHTML=data;   
          29.         document.getElementById("filediv").style.display="";   
          30.     });   
          31. }   
          32.        
          33. </script>  
          34. </head>  
          35.   
          36. <body>  
          37. <table border="1" cellpadding="3" width="50%">  
          38.     <tr>  
          39.         <td>Image</td>  
          40.         <td><input type="file" id="uploadImage" /></td>  
          41.         <td><input type="button" onclick="uploadFiles()" value="upload"/><div id="image.container">&nbsp;</div></td>  
          42.     </tr>  
          43.     <tr>  
          44.         <td>File</td>  
          45.         <td><input type="file" id="uploadFile" /></td>  
          46.         <td><input type="button" onclick="uploadFile()" value="upload"/><div id="file.container">&nbsp;</div></td>  
          47.     </tr>  
          48.     <tr>  
          49.         <td colspan="3"></td>  
          50.     </tr>  
          51. </table>  
          52. <img id="image" src="javascript:void(0);"/>  
          53. <div id="filediv" style="display:none;">  
          54. <a href="" id="file_a">上傳的文件</a>  
          55. </div>  
          56. </body>  
          57. </html>  
           

          添加進度條么,就需要用reverse ajax 進行配合使用了。

          posted @ 2010-01-24 13:42 shiwf 閱讀(4379) | 評論 (1)編輯 收藏

          2010年1月6日

          本文轉自:http://www.aygfsteel.com/xylz/

          DWR作為Ajax遠程調用的服務端得到了很多程序員的追捧,在DWR的2.x版本中已經集成了Guice的插件。

          老套了,我們還是定義一個HelloWorld的服務吧,哎,就喜歡HelloWorld,不怕被別人罵! 

          1 public interface HelloWorld {
          2 
          3     String sayHello();
          4 
          5     Date getSystemDate();
          6 }
          7 

          然后寫一個簡單的實現吧。 

           1 public class HelloWorldImpl implements HelloWorld {
           2 
           3     @Override
           4     public Date getSystemDate() {
           5         return new Date();
           6     }
           7 
           8     @Override
           9     public String sayHello() {
          10         return "Hello, guice";
          11     }
          12 }
          13 

          然后是與dwr有關的東西了,我們寫一個dwr的listener來注入我們的模塊。 

           1 package cn.imxylz.study.guice.web.dwr;
           2 
           3 import org.directwebremoting.guice.DwrGuiceServletContextListener;
           4 
           5 /**
           6  * @author xylz (www.imxylz.cn)
           7  * @version $Rev: 105 $
           8  */
           9 public class MyDwrGuiceServletContextListener extends DwrGuiceServletContextListener{
          10 
          11     @Override
          12     protected void configure() {
          13         bindRemotedAs("helloworld", HelloWorld.class).to(HelloWorldImpl.class).asEagerSingleton();
          14     }
          15 }
          16 

          這里使用bindRemotedAs來將我們的服務開放出來供dwr遠程調用。

          剩下的就是修改web.xml,需要配置一個dwr的Servlet并且將我們的listener加入其中??纯慈康膬热荨?nbsp;

           1 <?xml version="1.0" encoding="UTF-8"?>
           2 <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           3     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
           4     version="2.5">
           5 
           6     <display-name>guice-dwr</display-name>
           7     <description>xylz study project - guice</description>
           8 
           9     <listener>
          10         <listener-class>cn.imxylz.study.guice.web.dwr.MyDwrGuiceServletContextListener
          11         </listener-class>
          12     </listener>
          13     <servlet>
          14         <servlet-name>dwr-invoker</servlet-name>
          15         <servlet-class>org.directwebremoting.guice.DwrGuiceServlet</servlet-class>
          16         <init-param>
          17           <param-name>debug</param-name>
          18           <param-value>true</param-value>
          19         </init-param>
          20     </servlet>
          21     <servlet-mapping>
          22         <servlet-name>dwr-invoker</servlet-name>
          23         <url-pattern>/dwr/*</url-pattern>
          24     </servlet-mapping>
          25 
          26 </web-app>
          27 

          非常簡單,也非常簡潔,其中DwrGuiceServlet的debug參數只是為了調試方便才開放的,實際中就不用寫了。

          好了,看看我們的效果。

           1 <html>
           2 <head><title>dwr - test (www.imxylz.cn) </title>
           3   <script type='text/javascript' src='/guice-dwr/dwr/interface/helloworld.js'></script>
           4   <script type='text/javascript' src='/guice-dwr/dwr/engine.js'></script>
           5   <script type='text/javascript' src='/guice-dwr/dwr/util.js'></script>
           6   <script type='text/javascript'>
           7     var showHello = function(data){
           8         dwr.util.setValue('result',dwr.util.toDescriptiveString(data,1));   
           9     }
          10     var getSystemDate = function(data){
          11         dwr.util.setValue('systime',dwr.util.toDescriptiveString(data,2));   
          12     }
          13   </script>
          14   <style type='text/css'>
          15     input.button { border: 1px outset; margin: 0px; padding: 0px; }
          16     span { background: #ffffdd; white-space: pre; padding-left:20px;}
          17   </style>
          18 </head>
          19 <body onload='dwr.util.useLoadingMessage()'>
          20     <p>
          21     <h2>Guice and DWR</h2>
          22         <input class='button' type='button' value="Call HelloWorld 'sayHello' service" onclick="helloworld.sayHello(showHello)" />
          23         <span id='result' ></span>
          24     </p>
          25     <p>
          26         <input class='button' type='button' value="Call HelloWorld 'getSystemDate' service" onclick="helloworld.getSystemDate(getSystemDate)" />
          27         <span id='systime' ></span>
          28     </P>
          29 </body>
          30 </html>

          我們通過兩個按鈕來獲取我們的遠程調用的結果。

          posted @ 2010-01-06 18:46 shiwf 閱讀(468) | 評論 (0)編輯 收藏
           
               摘要: Guice真的無法享受企業級組件嗎,JavaEye里炮轟Guice的占絕大多數。但如果Guice能整合Spring,那么我們似乎可以做很多有意義的事了。那么開始Spring整合之旅吧。不過crazybob在整合方面極不配合,就給了我們一個單元測試類,然后讓我們自力更生。好在Guice本身足夠簡單。   首先還是來一個最簡單無聊的HelloWorld整合吧。   Hell...  閱讀全文
          posted @ 2010-01-06 16:39 shiwf 閱讀(2672) | 評論 (0)編輯 收藏
           

          Guice可真輕啊,所需的3Jar包才不到600k。但缺點就是必須JDK1.5以上,像我們公司有幾十個大大小小的Java項目,沒有一個是1.5的,有點感慨啊。廢話少說

           先建立一個service:

           

          IHelloService.java

          Java代碼
          1. package com.leo.service;  
          2.   
          3. import com.google.inject.ImplementedBy;  
          4. import com.leo.service.impl.HelloServiceImpl;  
          5.   
          6. /* 
          7.  * 采用annotation進行接口與實現類之間的綁定 
          8.  * 注意:接口與實現類之間綁定是必須的,如果只是單獨一個類,沒有接口, 
          9.  * 那么Guice會隱式的自動幫你注入。并且接口此是不應該聲明注入域范圍的, 
          10.  * 應該在其實現地方聲明 
          11.  * 
          12.  */  
          13. @ImplementedBy(HelloServiceImpl.class)  
          14. public interface IHelloService {  
          15.     public String sayHello(String str);  
          16. }  

           

           

          再來一個簡單的實現:

           

          HelloServiceImpl.java

          Java代碼
          1. package com.leo.service.impl;  
          2.   
          3. import com.google.inject.Singleton;  
          4. import com.leo.service.IHelloService;  
          5.   
          6. /* 
          7.  * 這里如果默認不用annotation標注其作用域,或在自定義的module也不指定的話 
          8.  * 默認的創建對象的方式是類似于Spring的prototype,在此處因為僅僅是一個stateless service 
          9.  * 我們用@Singleton來標注它,更多的作用域可看Guice文檔 
          10.  *  
          11.  * 注意:與標注@Singleton等效的工作也可以在自定義的module里來實現 
          12.  */  
          13.   
          14. @Singleton  
          15. public class HelloServiceImpl implements IHelloService {  
          16.   
          17.     public String sayHello(String str) {  
          18.         return new StringBuilder("Hello " + str + " !").toString();  
          19.     }  
          20.   
          21. }  

           

           

          Struts2的配置相信大家都會了,這里需要注意的是Struts2的工廠已經變了,默認是Spring現在我們要改成Guice,請看:

           

          struts.properties

          Java代碼
          1. struts.objectFactory = guice  
          2. #如果自已想實現Module接口,則下面注釋請去掉  
          3. #guice.module=com.leo.module.MyModule  
          4. struts.action.extension=  

           

           

          再來看看調用代碼,稍微比Spring簡潔了些:

           

          HelloAction.java

          Java代碼
          1. package com.leo.action;  
          2.   
          3. import com.google.inject.Inject;  
          4. import com.leo.service.IHelloService;  
          5. import com.opensymphony.xwork2.ActionSupport;  
          6.   
          7. public class HelloAction extends ActionSupport {  
          8.   
          9.     private static final long serialVersionUID = -338076402728419581L;  
          10.   
          11.     /* 
          12.      * 通過field字段進行注入,除此之外,還有construct, method注入均可 
          13.      */  
          14.     @Inject  
          15.     private IHelloService helloService;  
          16.   
          17.     private String message;  
          18.   
          19.     public String getMessage() {  
          20.         return message;  
          21.     }  
          22.   
          23.     public void setMessage(String message) {  
          24.         this.message = message;  
          25.     }  
          26.   
          27.     public String execute() {  
          28.         message = helloService.sayHello("leo");  
          29.         return SUCCESS;  
          30.     }  
          31.   
          32. }  

           

           

          struts.xml配置也是非常簡單:

           

          struts.xml

          Xml代碼
          1. <?xml version="1.0" encoding="UTF-8" ?>  
          2. <!DOCTYPE struts PUBLIC  
          3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
          4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
          5.   
          6. <struts>  
          7.     <package name="default" extends="struts-default">  
          8.         <action name="hello" class="com.leo.action.HelloAction">  
          9.             <result>index.jsp</result>  
          10.         </action>  
          11.     </package>  
          12. </struts>  

           

           

          到這里,算是大功告成了,Guice文檔在與Struts2整合部分例子有誤,而且郁悶的是,竟然連Guice的Filter需要在web.xml配置都沒有說,我把配好的web.xml弄出來給大家看看

           

          web.xml

          Xml代碼
          1. <?xml version="1.0" encoding="UTF-8"?>  
          2. <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
          3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
          4.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
          5.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
          6.   
          7.     <filter>  
          8.         <filter-name>guice</filter-name>  
          9.         <filter-class>  
          10.             com.google.inject.servlet.GuiceFilter  
          11.         </filter-class>  
          12.     </filter>  
          13.   
          14.     <filter>  
          15.         <filter-name>struts</filter-name>  
          16.         <filter-class>  
          17.             org.apache.struts2.dispatcher.FilterDispatcher  
          18.         </filter-class>  
          19.     </filter>  
          20.   
          21.     <filter-mapping>  
          22.         <filter-name>guice</filter-name>  
          23.         <url-pattern>/*</url-pattern>  
          24.     </filter-mapping>  
          25.   
          26.     <filter-mapping>  
          27.         <filter-name>struts</filter-name>  
          28.         <url-pattern>/*</url-pattern>  
          29.     </filter-mapping>  
          30.   
          31.     <welcome-file-list>  
          32.         <welcome-file>index.jsp</welcome-file>  
          33.     </welcome-file-list>  
          34. </web-app>  

           

           

          可以布署,運行了,輸入http://localhost:8080/struts2_guice/hello 就可以看到結果了。

           

          如果你覺得Annotation太麻煩,或不喜歡,也可以嘗試自己實現Guice的Module,以下是一個簡單的實現:

          MyModule.java

          Java代碼
          1. package com.leo.module;  
          2.   
          3. import com.google.inject.Binder;  
          4. import com.google.inject.Module;  
          5. import com.google.inject.Scopes;  
          6. import com.leo.service.IHelloService;  
          7. import com.leo.service.impl.HelloServiceImpl;  
          8.   
          9. /* 
          10.  * 如果你覺得Annotation有種支離破碎的感覺,別急,Guice還為你提供一種統一 
          11.  * 注入管理的自定義實現。在本例中,先前的IHelloService, HelloServiceImpl 
          12.  * 你現在可以完全將所有的Annotation去掉,然后實現Module接口的唯一一個方法 
          13.  * 實現如下 
          14.  */  
          15. public class MyModule implements Module {  
          16.   
          17.     public void configure(Binder binder) {  
          18.   
          19.         /* 
          20.          * 將接口IHelloService 與其實現HelloServiceImpl 綁定在一起 并且作用域為Scopes.SINGLETON 
          21.          * 在這里有多種配置方法,但因為是入門實例,不想說的太復雜。其中如果不配置作用域,默認就是類似于Spring 
          22.          * 的Scope="prototype" 
          23.          */  
          24.         binder.bind(IHelloService.class).to(HelloServiceImpl.class).in(  
          25.                 Scopes.SINGLETON);  
          26.     }  
          27.   
          28. }  

           

           

          運行效果完全一模一樣,因此團隊開發如果統一風格的話Guice確實能快速不少。但目前Guice僅僅只是一個IoC,遠遠沒有Spring所涉及的那么廣,但又正如Rod Johnson反復在其《J2EE without EJB》里強調:架構要永遠 simplest, simplest 再 simplest,因此你覺得夠用,就是最好的。

           

          總的來說,開發,運行的速度似乎又快了不少,但Guice真的能不能扛起其所說的下一代IoC容器,我們拭目以待吧。


          posted @ 2010-01-06 16:16 shiwf 閱讀(674) | 評論 (0)編輯 收藏

          2009年12月30日

          The Example Document and Beans

          In this example, we will unmarshall the same XML document that we used in the previous article:

          <?xml version="1.0"?>
          <catalog library="somewhere">
          <book>
          <author>Author 1</author>
          <title>Title 1</title>
          </book>
          <book>
          <author>Author 2</author>
          <title>His One Book</title>
          </book>
          <magazine>
          <name>Mag Title 1</name>
          <article page="5">
          <headline>Some Headline</headline>
          </article>
          <article page="9">
          <headline>Another Headline</headline>
          </article>
          </magazine>
          <book>
          <author>Author 2</author>
          <title>His Other Book</title>
          </book>
          <magazine>
          <name>Mag Title 2</name>
          <article page="17">
          <headline>Second Headline</headline>
          </article>
          </magazine>
          </catalog>

          The bean classes are also the same, except for one important change: In the previous article, I had declared these classes to have package scope -- primarily so that I could define all of them in the same source file! Using the Digester framework, this is no longer possible; the classes need to be declared as public (as is required for classes conforming to the JavaBeans specification):

          import java.util.Vector;
          public class Catalog {
          private Vector books;
          private Vector magazines;
          public Catalog() {
          books = new Vector();
          magazines = new Vector();
          }
          public void addBook( Book rhs ) {
          books.addElement( rhs );
          }
          public void addMagazine( Magazine rhs ) {
          magazines.addElement( rhs );
          }
          public String toString() {
          String newline = System.getProperty( "line.separator" );
          StringBuffer buf = new StringBuffer();
          buf.append( "--- Books ---" ).append( newline );
          for( int i=0; i<books.size(); i++ ){
          buf.append( books.elementAt(i) ).append( newline );
          }
          buf.append( "--- Magazines ---" ).append( newline );
          for( int i=0; i<magazines.size(); i++ ){
          buf.append( magazines.elementAt(i) ).append( newline );
          }
          return buf.toString();
          }
          }

          public class Book {
          private String author;
          private String title;
          public Book() {}
          public void setAuthor( String rhs ) { author = rhs; }
          public void setTitle(  String rhs ) { title  = rhs; }
          public String toString() {
          return "Book: Author='" + author + "' Title='" + title + "'";
          }
          }

          import java.util.Vector;
          public class Magazine {
          private String name;
          private Vector articles;
          public Magazine() {
          articles = new Vector();
          }
          public void setName( String rhs ) { name = rhs; }
          public void addArticle( Article a ) {
          articles.addElement( a );
          }
          public String toString() {
          StringBuffer buf = new StringBuffer( "Magazine: Name='" + name + "' ");
          for( int i=0; i<articles.size(); i++ ){
          buf.append( articles.elementAt(i).toString() );
          }
          return buf.toString();
          }
          }

          public class Article {
          private String headline;
          private String page;
          public Article() {}
          public void setHeadline( String rhs ) { headline = rhs; }
          public void setPage(     String rhs ) { page     = rhs; }
          public String toString() {
          return "Article: Headline='" + headline + "' on page='" + page + "' ";
          }
          }












          import org.apache.commons.digester.*;
          import java.io.*;
          import java.util.*;
          public class DigesterDriver {
          public static void main( String[] args ) {
          try {
          Digester digester = new Digester();
          digester.setValidating( false );
          digester.addObjectCreate( "catalog", Catalog.class );
          digester.addObjectCreate( "catalog/book", Book.class );
          digester.addBeanPropertySetter( "catalog/book/author", "author" );
          digester.addBeanPropertySetter( "catalog/book/title", "title" );
          digester.addSetNext( "catalog/book", "addBook" );
          digester.addObjectCreate( "catalog/magazine", Magazine.class );
          digester.addBeanPropertySetter( "catalog/magazine/name", "name" );
          digester.addObjectCreate( "catalog/magazine/article", Article.class );
          digester.addSetProperties( "catalog/magazine/article", "page", "page" );
          digester.addBeanPropertySetter( "catalog/magazine/article/headline" );
          digester.addSetNext( "catalog/magazine/article", "addArticle" );
          digester.addSetNext( "catalog/magazine", "addMagazine" );
          File input = new File( args[0] );
          Catalog c = (Catalog)digester.parse( input );
          System.out.println( c.toString() );
          } catch( Exception exc ) {
          exc.printStackTrace();
          }
          }
          }

          After instantiating the Digester, we specify that it should not validate the XML document against a DTD -- because we did not define one for our simple Catalog document. Then we specify the patterns and the associated rules: the ObjectCreateRule creates an instance of the specified class and pushes it onto the parse stack. The SetPropertiesRule sets a bean property to the value of an XML attribute of the current element -- the first argument to the rule is the name of the attribute, the second, the name of the property.

          Whereas SetPropertiesRule takes the value from an attribute, BeanPropertySetterRule takes the value from the raw character data nested inside of the current element. It is not necessary to specify the name of the property to set when using BeanPropertySetterRule: it defaults to the name of the current XML element. In the example above, this default is being used in the rule definition matching the catalog/magazine/article/headline pattern. Finally, the SetNextRule pops the object on top of the parse stack and passes it to the named method on the object below it -- it is commonly used to insert a finished bean into its parent.

          Note that it is possible to register several rules for the same pattern. If this occurs, the rules are executed in the order in which they are added to the Digester -- for instance, to deal with the <article> element, found at catalog/magazine/article, we first create the appropriate article bean, then set the page property, and finally pop the completed article bean and insert it into its magazine parent.

          Invoking Arbitrary Functions

          It is not only possible to set bean properties, but to invoke arbitrary methods on objects in the stack. This is accomplished using the CallMethodRule to specify the method name and, optionally, the number and type of arguments passed to it. Subsequent specifications of the CallParamRule define the parameter values to be passed to the invoked functions. The values can be taken either from named attributes of the current XML element, or from the raw character data contained by the current element. For instance, rather than using the BeanPropertySetterRule in the DigesterDriver implementation above, we could have achieved the same effect by calling the property setter explicitly, and passing the data as parameter:

             digester.addCallMethod( "catalog/book/author", "setAuthor", 1 );
          digester.addCallParam( "catalog/book/author", 0 );

          The first line gives the name of the method to call (setAuthor()), and the expected number of parameters (1). The second line says to take the value of the function parameter from the character data contained in the <author> element and pass it as first element in the array of arguments (i.e., the array element with index 0). Had we also specified an attribute name (e.g., digester.addCallParam( "catalog/book/author", 0, "author" );), the value would have been taken from the respective attribute of the current element instead.

          One important caveat: confusingly, digester.addCallMethod( "pattern", "methodName", 0 ); does not specify a call to a method taking no arguments -- instead, it specifies a call to a method taking one argument, the value of which is taken from the character data of the current XML element! We therefore have yet another way to implement a replacement for BeanPropertySetterRule:

             digester.addCallMethod( "catalog/book/author", "setAuthor", 0 );

           

          To call a method that truly takes no parameters, use digester.addCallMethod( "pattern", "methodName" );.




          Summary of Standard Rules



          Below are brief descriptions of all of the standard rules.

          Creational

          • ObjectCreateRule: Creates an object of the specified class using its default constructor and pushes it onto the stack; it is popped when the element completes. The class to instantiate can be given through a class object or the fully-qualified class name.

          • FactoryCreateRule: Creates an object using a specified factory class and pushes it onto the stack. This can be useful for classes that do not provide a default constructor. The factory class must implement the org.apache.commons.digester.ObjectCreationFactory interface.

          Property Setters

          • SetPropertiesRule: Sets one or several named properties in the top-level bean using the values of named XML element attributes. Attribute names and property names are passed to this rule in String[] arrays. (Typically used to handle XML constructs like <article page="10">.)

          • BeanPropertySetterRule: Sets a named property on the top-level bean to the character data enclosed by the current XML element. (Example: <page>10</page>.)

          • SetPropertyRule: Sets a property on the top-level bean. Both the property name, as well as the value to which this property will be set, are given as attributes to the current XML element. (Example: <article key="page" value="10" />.)

          Parent/Child Management

          • SetNextRule: Pops the object on top of the stack and passes it to a named method on the object immediately below. Typically used to insert a completed bean into its parent.

          • SetTopRule: Passes the second-to-top object on the stack to the top-level object. This is useful if the child object exposes a setParent method, rather than the other way around.

          • SetRootRule: Calls a method on the object at the bottom of the stack, passing the object on top of the stack as argument.

          Arbitrary Method Calls

          • CallMethodRule: Calls an arbitrary named method on the top-level bean. The method may take an arbitrary set of parameters. The values of the parameters are given by subsequent applications of the CallParamRule.

          • CallParamRule: Represents the value of a method parameter. The value of the parameter is either taken from a named XML element attribute, or from the raw character data enclosed by the current element. This rule requires that its position on the parameter list is specified by an integer index.

          Specifying Rules in XML: Using the xmlrules Package

          Related Reading

          Programming Jakarta Struts
          By Chuck Cavaness

          So far, we have specified the patterns and rules programmatically at compile time. While conceptually simple and straightforward, this feels a bit odd: the entire framework is about recognizing and handling structure and data at run time, but here we go fixing the behavior at compile time! Large numbers of fixed strings in source code typically indicate that something is being configured (rather than programmed), which could be (and probably should be) done at run time instead.

          The org.apache.commons.digester.xmlrules package addresses this issue. It provides the DigesterLoader class, which reads the pattern/rule-pairs from an XML document and returns a digester already configured accordingly. The XML document configuring the Digester must comply with the digester-rules.dtd, which is part of the xmlrules package.

          Below is the contents of the configuration file (named rules.xml) for the example application. I want to point out several things here.

          Patterns can be specified in two different ways: either as attributes to each XML element representing a rule, or using the <pattern> element. The pattern defined by the latter is valid for all contained rule elements. Both ways can be mixed, and <pattern> elements can be nested -- in either case, the pattern defined by the child element is appended to the pattern defined in the enclosing <pattern> element.

          The <alias> element is used with the <set-properties-rule> to map an XML attribute to a bean property.

          Finally, using the current release of the Digester package, it is not possible to specify the BeanPropertySetterRule in the configuration file. Instead, we are using the CallMethodRule to achieve the same effect, as explained above.

          <?xml version="1.0"?>
          <digester-rules>
          <object-create-rule pattern="catalog" classname="Catalog" />
          <set-properties-rule pattern="catalog" >
          <alias attr-name="library" prop-name="library" />
          </set-properties-rule>
          <pattern value="catalog/book">
          <object-create-rule classname="Book" />
          <call-method-rule pattern="author" methodname="setAuthor"
          paramcount="0" />
          <call-method-rule pattern="title" methodname="setTitle"
          paramcount="0" />
          <set-next-rule methodname="addBook" />
          </pattern>
          <pattern value="catalog/magazine">
          <object-create-rule classname="Magazine" />
          <call-method-rule pattern="name" methodname="setName" paramcount="0" />
          <pattern value="article">
          <object-create-rule classname="Article" />
          <set-properties-rule>
          <alias attr-name="page" prop-name="page" />
          </set-properties-rule>
          <call-method-rule pattern="headline" methodname="setHeadline"
          paramcount="0" />
          <set-next-rule methodname="addArticle" />
          </pattern>
          <set-next-rule methodname="addMagazine" />
          </pattern>
          </digester-rules>

          Since all the actual work has now been delegated to the Digester and DigesterLoader classes, the driver class itself becomes trivially simple. To run it, specify the catalog document as the first command line argument, and the rules.xml file as the second. (Confusingly, the DigesterLoader will not read the rules.xml file from a File or an org.xml.sax.InputSource, but requires a URL -- the File reference in the code below is therefore transformed into an equivalent URL.)

          import org.apache.commons.digester.*;
          import org.apache.commons.digester.xmlrules.*;
          import java.io.*;
          import java.util.*;
          public class XmlRulesDriver {
          public static void main( String[] args ) {
          try {
          File input = new File( args[0] );
          File rules = new File( args[1] );
          Digester digester = DigesterLoader.createDigester( rules.toURL() );
          Catalog catalog = (Catalog)digester.parse( input );
          System.out.println( catalog.toString() );
          } catch( Exception exc ) {
          exc.printStackTrace();
          }
          }
          }

          Conclusion

          This concludes our brief overview of the Jakarta Commons Digester package. Of course, there is more. One topic ignored in this introduction are XML namespaces: Digester allows you to specify rules that only act on elements defined within a certain namespace.

          We mentioned briefly the possibility of developing custom rules, by extending the Rule class. The Digester class exposes the customary push(), peek(), and pop() methods, giving the individual developer freedom to manipulate the parse stack directly.

          Lastly, note that there is an additional package providing a Digester implementation which deals with RSS (Rich-Site-Summary)-formatted newsfeeds. The Javadoc tells the full story.

          References

          Philipp K. Janert is a software project consultant, server programmer, and architect.



          posted @ 2009-12-30 11:29 shiwf 閱讀(491) | 評論 (0)編輯 收藏
           

          Beanutils用了魔術般的反射技術,實現了很多夸張有用的功能,都是C/C++時代不敢想的。無論誰的項目,始終一天都會用得上它。我算是后知后覺了,第一回看到它的時候居然錯過。

          1.屬性的動態getter,setter

          在這框架滿天飛的年代,不能事事都保證執行getter,setter函數了,有時候屬性是要需要根據名字動態取得的,就像這樣:  
          BeanUtils.getProperty(myBean,"code");
          而BeanUtils更強的功能是直接訪問內嵌對象的屬性,只要使用點號分隔。
          BeanUtils.getProperty(orderBean, "address.city");
          相比之下其他類庫的BeanUtils通常都很簡單,不能訪問內嵌的對象,所以經常要用Commons BeanUtils替換它們。
          BeanUtils還支持List和Map類型的屬性。如下面的語法即可取得顧客列表中第一個顧客的名字
          BeanUtils.getProperty(orderBean, "customers[1].name");
          其中BeanUtils會使用ConvertUtils類把字符串轉為Bean屬性的真正類型,方便從HttpServletRequest等對象中提取bean,或者把bean輸出到頁面。
          而PropertyUtils就會原色的保留Bean原來的類型。

          2.beanCompartor 動態排序

          還是通過反射,動態設定Bean按照哪個屬性來排序,而不再需要在bean的Compare接口進行復雜的條件判斷。
          List peoples = ...; // Person對象的列表Collections.sort(peoples, new BeanComparator("age"));

          如果要支持多個屬性的復合排序,如"Order By lastName,firstName"

          ArrayList sortFields = new ArrayList();sortFields.add(new BeanComparator("lastName"));
          sortFields.add(new BeanComparator("firstName"));
          ComparatorChain multiSort = new ComparatorChain(sortFields);
          Collections.sort(rows,multiSort);

          其中ComparatorChain屬于jakata commons-collections包。
          如果age屬性不是普通類型,構造函數需要再傳入一個comparator對象為age變量排序。
          另外, BeanCompartor本身的ComparebleComparator, 遇到屬性為null就會拋出異常, 也不能設定升序還是降序。
          這個時候又要借助commons-collections包的ComparatorUtils.

             Comparator mycmp = ComparableComparator.getInstance();
             mycmp = ComparatorUtils.nullLowComparator(mycmp);  //允許null
             mycmp = ComparatorUtils.reversedComparator(mycmp); //逆序
             Comparator cmp = new BeanComparator(sortColumn, mycmp);

          3.Converter 把Request或ResultSet中的字符串綁定到對象的屬性

             經常要從request,resultSet等對象取出值來賦入bean中,下面的代碼誰都寫膩了,如果不用MVC框架的綁定功能的話。

             String a = request.getParameter("a");   bean.setA(a);   String b = ....

          不妨寫一個Binder:

               MyBean bean = ...;    HashMap map = new HashMap();    Enumeration names = request.getParameterNames();    while (names.hasMoreElements())    {      String name = (String) names.nextElement();      map.put(name, request.getParameterValues(name));    }    BeanUtils.populate(bean, map);

              其中BeanUtils的populate方法或者getProperty,setProperty方法其實都會調用convert進行轉換。
              但Converter只支持一些基本的類型,甚至連java.util.Date類型也不支持。而且它比較笨的一個地方是當遇到不認識的類型時,居然會拋出異常來。
              對于Date類型,我參考它的sqldate類型實現了一個Converter,而且添加了一個設置日期格式的函數。
          要把這個Converter注冊,需要如下語句:

              ConvertUtilsBean convertUtils = new ConvertUtilsBean();
             DateConverter dateConverter = new DateConverter();
             convertUtils.register(dateConverter,Date.class);



          //因為要注冊converter,所以不能再使用BeanUtils的靜態方法了,必須創建BeanUtilsBean實例
          BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils,new PropertyUtilsBean());
          beanUtils.setProperty(bean, name, value);
          4 其他功能
          4.1 PropertyUtils,當屬性為Collection,Map時的動態讀?。?/span>
           
          Collection: 提供index
             BeanUtils.getIndexedProperty(orderBean,"items",1);
          或者
            BeanUtils.getIndexedProperty(orderBean,"items[1]");

          Map: 提供Key Value
            BeanUtils.getMappedProperty(orderBean, "items","111");//key-value goods_no=111
          或者
            BeanUtils.getMappedProperty(orderBean, "items(111)")
           
          4.2 PropertyUtils,獲取屬性的Class類型
               public static Class getPropertyType(Object bean, String name)
           
          4.3 ConstructorUtils,動態創建對象
                public static Object invokeConstructor(Class klass, Object arg)
          4.4 MethodUtils,動態調用方法
              MethodUtils.invokeMethod(bean, methodName, parameter);
          4.5 動態Bean 用DynaBean減除不必要的VO和FormBean 
          posted @ 2009-12-30 11:24 shiwf 閱讀(43726) | 評論 (4)編輯 收藏
           

          1.BeanUtils基本用法:

          java 代碼
          1. package com.beanutil;   
          2.   
          3. import java.util.Map;   
          4.   
          5. public class User {   
          6.   
          7.     private Integer id;   
          8.     private Map map;   
          9.     private String username;   
          10.     public Integer getId() {   
          11.         return id;   
          12.     }   
          13.     public void setId(Integer id) {   
          14.         this.id = id;   
          15.     }   
          16.     public Map getMap() {   
          17.         return map;   
          18.     }   
          19.     public void setMap(Map map) {   
          20.         this.map = map;   
          21.     }   
          22.     public String getUsername() {   
          23.         return username;   
          24.     }   
          25.     public void setUsername(String username) {   
          26.         this.username = username;   
          27.     }   
          28.        
          29.        
          30. }  
          java 代碼
          1. public class Order {   
          2.     private User user;   
          3.     private Integer id;   
          4.     private String desc;   
          5.     public String getDesc() {   
          6.         return desc;   
          7.     }   
          8.     public void setDesc(String desc) {   
          9.         this.desc = desc;   
          10.     }   
          11.     public Integer getId() {   
          12.         return id;   
          13.     }   
          14.     public void setId(Integer id) {   
          15.         this.id = id;   
          16.     }   
          17.     public User getUser() {   
          18.         return user;   
          19.     }   
          20.     public void setUser(User user) {   
          21.         this.user = user;   
          22.     }   
          23.        
          24.   
          25. }  

           

          java 代碼
          1.   
          2. import java.util.HashMap;   
          3. import java.util.Map;   
          4.   
          5. import org.apache.commons.beanutils.BeanUtils;   
          6.   
          7. public class Test {   
          8.        
          9.     private User user = new User();   
          10.     private Order order1 = new Order();   
          11.     private Order order2 = new Order();   
          12.     private Order order3 = new Order();   
          13.     private Map map = new HashMap();   
          14.     private User user1 = new User();   
          15.   
          16.     public Test(){   
          17.         init();   
          18.     }   
          19.     public static void main(String[] args) throws Exception{   
          20.         Test test = new Test();   
          21.         //輸出某個對象的某個屬性   
          22.         System.out.println(BeanUtils.getProperty(test.user, "username"));   
          23.            
          24.         //輸出某個對象的內嵌屬性,只要使用點號分隔   
          25.         System.out.println(BeanUtils.getProperty(test.order1, "user.username"));   
          26.            
          27.         //BeanUtils還支持List和Map類型的屬性,對于Map類型,則需要以"屬性名(key值)"的   
          28.         //對于Indexed,則為"屬性名[索引值]",注意對于ArrayList和數組都可以用一樣的方式進行操作   
          29.         System.out.println(BeanUtils.getProperty(test.user1, "map(order2).desc"));   
          30.   
          31.         //拷貝對象的屬性值   
          32.         User tempUser = new User();   
          33.         BeanUtils.copyProperties(tempUser, test.user1);   
          34.            
          35.         System.out.println(tempUser.getUsername());   
          36.         System.out.println(tempUser.getId());   
          37.            
          38.            
          39.            
          40.            
          41.     }   
          42.        
          43.     //初始化   
          44.     public void init(){   
          45.            
          46.            
          47.         user.setId(0);   
          48.         user.setUsername("zhangshan");   
          49.            
          50.            
          51.         order1.setId(1);   
          52.         order1.setDesc("order1");   
          53.         order1.setUser(user);   
          54.            
          55.            
          56.            
          57.         order2.setId(2);   
          58.         order2.setDesc("order2");   
          59.         order2.setUser(user);   
          60.            
          61.            
          62.         order3.setId(3);   
          63.         order3.setDesc("order3");   
          64.         order3.setUser(user);   
          65.            
          66.            
          67.         map.put("order1", order1);   
          68.         map.put("order2", order2);   
          69.         map.put("order3", order3);   
          70.            
          71.            
          72.         user1.setId(1);   
          73.         user1.setUsername("lisi");   
          74.         user1.setMap(map);   
          75.            
          76.            
          77.     }   
          78. }   

           

          輸出結果為:

          zhangshan
          zhangshan
          order2
          lisi
          1

           

          2. BeanCompartor 動態排序

          A:動態設定Bean按照哪個屬性來排序,而不再需要再實現bean的Compare接口進行復雜的條件判斷

          java 代碼
          1. //動態設定Bean按照哪個屬性來排序,而不再需要再實現bean的Compare接口進行復雜的條件判斷   
          2.         List<order></order> list = new ArrayList<order></order>();   
          3.            
          4.         list.add(test.order2);   
          5.         list.add(test.order1);   
          6.         list.add(test.order3);   
          7.            
          8.         //未排序前   
          9.         for(Order order : list){   
          10.             System.out.println(order.getId());   
          11.         }   
          12.         //排序后   
          13.         Collections.sort(list, new BeanComparator("id"));   
          14.         for(Order order : list){   
          15.             System.out.println(order.getId());   
          16.         }  

           

          B:支持多個屬性的復合排序

          java 代碼
          1. //支持多個屬性的復合排序   
          2.         List <beancomparator></beancomparator> sortFields = new ArrayList<beancomparator></beancomparator>();    
          3.         sortFields.add(new BeanComparator("id"));   
          4.         sortFields.add(new BeanComparator("desc"));   
          5.         ComparatorChain multiSort = new ComparatorChain(sortFields);   
          6.         Collections.sort(list, multiSort);   
          7.            
          8.         for(Order order : list){   
          9.             System.out.println(order.getId());   
          10.         }  

           

          C:使用ComparatorUtils進一步指定排序條件

          上面的排序遇到屬性為null就會拋出異常, 也不能設定升序還是降序。
            不過,可以借助commons-collections包的ComparatorUtils
            BeanComparator,ComparableComparator和ComparatorChain都是實現了Comparator這個接口

          java 代碼
          1. //上面的排序遇到屬性為null就會拋出異常, 也不能設定升序還是降序。   
          2.         //不過,可以借助commons-collections包的ComparatorUtils   
          3.         //BeanComparator,ComparableComparator和ComparatorChain都是實現了Comparator這個接口   
          4.         Comparator mycmp = ComparableComparator.getInstance();      
          5.         mycmp = ComparatorUtils.nullLowComparator(mycmp);  //允許null      
          6.         mycmp = ComparatorUtils.reversedComparator(mycmp); //逆序      
          7.         Comparator cmp = new BeanComparator("id", mycmp);   
          8.         Collections.sort(list, cmp);   
          9.         for(Order order : list){   
          10.             System.out.println(order.getId());   
          11.         }  
          posted @ 2009-12-30 11:20 shiwf 閱讀(958) | 評論 (0)編輯 收藏

          2009年12月14日

               摘要:  CXF 最新版本:2.2.2開源服務框架,可以通過API,如JAX-WS,構建和開發服務。服務可以使多種協議的,例如SOAP, XML/HTTP, RESTful HTTP,  CORBA,并可以工作與多種傳輸協議之上,如HTTP,JMS,JBI。 主要特性 ·支持Webservice標準:包括SOAP, the Basic Profile, WSDL, ...  閱讀全文
          posted @ 2009-12-14 21:24 shiwf 閱讀(2575) | 評論 (0)編輯 收藏
           
          Copyright © shiwf Powered by: 博客園 模板提供:滬江博客
          主站蜘蛛池模板: 泾源县| 稻城县| 永丰县| 乌什县| 松滋市| 汝州市| 霍山县| 慈利县| 怀仁县| 忻城县| 遵义县| 东港市| 万全县| 富阳市| 内乡县| 保亭| 河曲县| 如东县| 望奎县| 闻喜县| 赞皇县| 美姑县| 蕲春县| 广饶县| 灵石县| 元阳县| 泗水县| 廊坊市| 思南县| 成武县| 黔西| 穆棱市| 洪洞县| 平和县| 温泉县| 鄂伦春自治旗| 灵川县| 富平县| 潜山县| 大姚县| 宁陕县|