seasun  
在不断模仿、思考、总结中一步一步进步!
公告
  •     我的blog中的部分资源是来自于网络上,如果您认为侵犯了您的权利,请及时联系我我会尽快删除!E-MAIL:shiwenfeng@aliyun.com和QQ:281340916,欢迎交流。

日历
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

常用链接

随笔分类

good blog author

积分与排名

  • 积分 - 80634
  • 排名 - 698

最新评论

阅读排行榜

 

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 阅读(4677) | 评论 (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 阅读(2048) | 评论 (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 阅读(4349) | 评论 (1)编辑 收藏

2010年1月6日

本文转自:http://www.blogjava.net/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加入其中。看看全部的内容。 

 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 阅读(442) | 评论 (0)编辑 收藏
 
     摘要: Guice真的无法享受企业级组件吗,JavaEye里炮轰Guice的占绝大多数。但如果Guice能整合Spring,那么我们似乎可以做很多有意义的事了。那么开始Spring整合之旅吧。不过crazybob在整合方面极不配合,就给了我们一个单元测试类,然后让我们自力更生。好在Guice本身足够简单。   首先还是来一个最简单无聊的HelloWorld整合吧。   Hell...  阅读全文
posted @ 2010-01-06 16:39 shiwf 阅读(2636) | 评论 (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 阅读(647) | 评论 (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 阅读(457) | 评论 (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时的动态读取:
 
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 阅读(43613) | 评论 (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 阅读(912) | 评论 (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 阅读(2539) | 评论 (0)编辑 收藏
 
Copyright © shiwf Powered by: 博客园 模板提供:沪江博客