SEAM|SEAM IN ACTION有空就翻翻
说实话,关于SEAM的书不多。
在网上搜seam in action中文版,有,在csdn,花3分下下来,假的。是中文的参考文档(Seam reference)。找骂。
自己也真想细致地了解一下SEAM的前世今生,所以试着自己翻一下。
目地只是为了学习和分享,请尊重英文原作者的版权。
========
Foreword
The most challenging part of being a developer on the Seam project isn’t writing the
code—it’s trying to explain Seam to new users. There’s a large gap that a Seam neophyte
must cross to really “get” what Seam is about. The problem isn’t that Seam is
overly complex, or that it requires an esoteric skill set. Seam puts together a number
of ideas that are unfamiliar to mainstream Java developers. Many of those ideas challenge
the common wisdom of enterprise Java development.
对于SEAM,最难的不是写代码,而是将SEAM解释给新人听。
并不是因为SEAM过于复杂,也不是需要很牛的技术,只是SEAM带有一些主流开发者不是很熟悉的思想。很多思想是对企业JAVA开发的普通知识的挑战。
To start with, Seam fills a gap not many Java developers realize exists. We are so
accustomed to working with a half dozen disintegrated technologies that a truly integrated
application framework seems foreign to us. This disintegration is most painfully
clear at the persistence layer. Where ineffective caching and lazy instantiation
issues plague most applications, Seam actually gets it right. When you consider that
the creators of Seam were the brains behind Hibernate, that’s not hard to believe!
【SEAM|SEAM IN ACTION有空就翻翻】很多JAVAA开发者没有意识到,我们缺少一个真正完整的框架,而分散,尤其是数据存储层如果不集成进来的话,真是一种痛。因为低效的缓存,懒实例化问题会连累很多应用。SEAM纠正了这些,如果你知道SEAM与Hibernate是同一作者,这一切就不难相信了。
Then you’ve got Seam’s dynamic bidirection injection (bijection), which is radically
different from the static injection offered by the popular dependency injection
frameworks. And we haven’t even mentioned the clever stateful components in a
world where the prevailing technologies force all applications into a multilayered
stateless architecture regardless of whether that architecture suits the application
being developed.
SEAM的双向注入bidirection injection (bijection),与依赖注入框架的表态注入有很大不同。有状态部件相对于那些无视应用本身特点的无状态框架也是聪明了不少。
We’re just scratching the surface, and already we can see that Seam offers a vision
that’s so different from the status quo that guiding a new Seam user becomes a huge
challenge. As a result, few introductions to Seam go beyond the basics, presenting the
ABCs of the technology without showing how to put the letters together to make words
and sentences. Seam in Action is the first Seam book to capture the spirit of Seam and
show you how to put those words and sentences together the way we on the Seam
team intended the technology to be used.
对于SEAM的新手来说,的确有些挑战。为数很少的入门书也没有真正将SEAM解析清楚。Seam in Action是第一本讲到精髓的。
What impresses me most about the book you’re holding in your hands is that it
doesn’t blindly toe the Seam party line. Dan Allen has painstakingly broken Seam
down to its core concepts and reassembled them in a way that is fresh and unique.
Seam in Action isn’t a simple-minded regurgitation of the Seam reference documentation.
Instead, it’s a perfect companion to it, showing how to understand Seam and
best apply it to your own applications.
Dan Allen真是费了不少心血,将SEAM拆碎了又拼起来给大家看。而不是简单地将Seam reference文档提取出一些来讲,而是努力成为了Seam reference的伴侣,从另一个角度来帮助用户理解SEAM并应用到项目中。
Seam can help you code better, more functional applications. It can help you work
faster, and it can help you code your applications with a simpler, easier-to-manage
architecture. But you’ll only reap those benefits if you take the time to learn how to
best apply the technology. Seam in Action is the perfect guide to get you to the point
where you can apply Seam to its full potential.
SEAM这一简单、易于管理的框架能让你代码美、功能强、速度快。Seam in Action是完美的指导,可向你展示SEAM的全部潜能。
If you’re up to the challenge, then, to shamelessly borrow the analogy of the book,
I invite you to step up to the first tee—and take a swing.
(翻译到这里有趣的事就来了。我感觉这本书的作者或注者不少都是诗人出身。有的地方也明显是High的时候写出来的。翻到这里的时候也只能别太认真了)
如果你勇于面对这个挑战的话,就快来挥挥杆吧!(本书中的例子就是关于高尔夫的)
NORMAN RICHARDS
Senior Engineer, Red Hat
========
Preface
We can’t solve problems by using the same kind of thinking we used when we created them.
—Albert Einstein
我们是不能用系铃的方法去解铃的。
--老爱
As I write this passage, I’m flying over the Atlantic Ocean on my way back from Europe
to the United States for the second time in a month. This trip was to Tuscany for a meeting
to discuss Seam’s future;
the previous trip had been to Zurich, where I spoke about
Seam at the Jazoon ’08 conference. The first trip was especially significant to me because
it marked the first time in the 30 years of my life that I’ve traveled outside of North America.
I was beginning to think that day would never come, but it did, thanks to Seam. (And
because my brother purchased the ticket to get me there. Thanks, Kevin!)
有一个好兄弟是很重要的。尤其是有Kevin这样的兄弟。
You might think I’m ridiculous for attributing this milestone to Seam. After all, how
can a framework motivate a person to embark on an unprecedented trip? Before you
call me crazy, let me explain how I got involved in Seam and how it influenced me to
expand my horizons.
我是怎样卷入SEAM的呢?
Around the time Seam was being developed, I was spending my days banging my
head on a project built using Spring and JSF. For more than a year, I felt stuck in a rut
trying to manage the application’s state, wrestling with irrelevant decisions such as
whether to name a business object a Manager or a Service, and rationalizing how many
layers to use and which layer should take ownership of a given task. All of these distractions
held back the project and my growth. I kept looking for some way out.
我以前是搞Spring and JSF的,在长达一年以上的时间里,我一直困惑于应用程序的状态。飘乎于是否用Manager or a Service来命名一个业务对象,该用几层才好,以及哪一层为主控。这些事一直拖累着我。
The spark that attracted me to Seam is the fine-grained control it provides over JSF
requests through its page descriptor. The reason I stuck with Seam (and ultimately
decided to write about it) goes well beyond the voids it filled for me at the time.
吸引了我的SEAM的火花是使用页描述符,通过JSF请求而实现的细粒度控制。我乐于摆弄SEAM以到决定写点什么的原因,我相信就和现在的译者或读者一样。
Seam has clout because it follows a consistent approach without imposing arbitrary
restrictions. It leverages annotations, interceptors, XHTML-based templates, and
JSF components to give you the most bang for your keystroke. It provides access to
objects when and where you need them and manages them so you don’t have to. It
also helps establish continuity from one page request to the next. Above all, it gives
you freedom to organize the application as it suits you and to choose the tools you
want to use to build it: Java or Groovy, XML or annotations, JavaScript or rich widgets,
built-in or custom components, and so on.
SEAM拽是因为提供了一系列方法而不是对人强加限制。可使用annotations,interceptors,基于XHTML的模板,JSF部件,当你要访问对象时,它提供给你并帮你管理。并可以建立多页切换时的连续性,你可以自由地选择工具如
Java or Groovy, XML or annotations, JavaScript or rich widgets,built-in or custom components。
But we have a tendency to get caught up in the word framework and forget the real
reason we’re writing software: to serve the needs of our users or our clients’ users.
That’s the angle you have to take going into learning one of these tools.
框架的时代,我们都快忘记我们为什么要写软件了:是为了满足用户的需要。
Users don’t want to spend their days paging through endless result sets and could
care less if you’re having a problem with lazy initialization exceptions in the view. They
want mature software. They want advanced searches, reports in PDF or Excel, charts,
emails, file uploads, dynamic graphics, wizards, workspaces, and so on. Basically, they
want the stuff that’s really hard to develop, or at least harder than feeding the database
through a CRUD generation tool. Seam gives you the CRUD generation tool, which gets
you developing immediately, and it also provides the extra stuff.
用户不想总是看到没完没了的结果集及懒加载异常。他们想要成熟的软件、高级的搜索、PDF报告、Excel或图表、邮件、文件上传、动态图形、向导、工作空间,等等。总之,他们需要的这些都挺难搞定,至少用通用的数据库CRUD工具不行。而SEAM提供的CRUD工具可以快速开发这些来,以及其它的好东东。
Seam is worth knowing because it touches on nearly every aspect of Java EE. Sure,
you have a lot to learn, but Seam makes every facet of the platform remarkably accessible
and gets you working on the advanced parts of your application early in the project.
You no longer have to dread those wild and crazy requirements that the user
dreams up. Instead, you feel empowered to write applications—and you’ll get to the
feature wish lists.
知道了SEAM你也就知道了Java EE的方方面面。它可以让你在项目的早期就先进起来。你不用怕用户产生的新的需求,因为都跳不出SEAM的外延。
As an integration framework, Seam keeps a vast number of technologies close at
hand and accessible. As a result, you find yourself trying out technologies you never
thought you’d use, and you witness your application and skill set maturing quickly. You
also start introducing new styles of interaction into your application, such as the eventobserver
model or something as revolutionary as Ajax Push. You get used to venturing
into new territory, without having to abandon the familiar, and it affects your general
attitude toward life.
作为一个集成的框架,SEAM包含了很多新技术,你会发现你的应用程序建立得又快又强大。你还可以增加新的成分如eventobserver model或Ajax Push。面对新的领域你的胆子变大了,SEAM也会改变你的人生态度。
That brings me back to my original statement. Seam is the driver that finally
launched me out of North America. It also kick-started my writing and consulting
career, got me involved in a successful open source project, and allowed me to meet
interesting and talented people. How will Seam change your career? How will it change
your life?
是SEAM让我告别平庸,开始了写作和咨询生涯,加入了成功的开源项目,见到了有趣的及天才的人们。
SEAM会怎么改变你呢?
Somewhere over the Atlantic, July 2008
大西洋上空
========
Acknowledgments
While writing this book, I made many promises to myself and others about what I’d
do when I finished. The most important of those promises was to acknowledge everyone
who made this book possible. Of course, I’m grateful to have you as a reader. But
you should appreciate those people who got this book out on the shelves and into
your hands.
自己重要,支持者重要,当然读者也重要。
The first and last person I want to thank is my wife, Sarah. If it weren’t for her help,
you wouldn’t be holding this book. I have no idea where to even begin thanking her.
She pushed me to believe in myself, kept me motivated when the end kept moving
further away, tolerated being inundated with Seam and my relentless questioning
about how to structure the book, edited drafts, assembled the index, provided therapy,
made sure I ate, and took care of countless chores I let slip. What meant the most
is that she put my project before her own, something I look forward to doing for her
now. Please help me in thanking her.
有个好老婆最重要。
Writing a book puts a tremendous strain on relationships. I would like to thank all
my friends and family for supporting me in this endeavor and having faith that I would
eventually come out of my hole and once again answer phone calls, hang out, and talk
about something other than writing a book. I am forever indebted to my parents, James
and Mary Allen, for extending me every opportunity in my life to be successful. You
only get one childhood and they made it both a rewarding and a memorable one. Mom
and Dad, thanks for passing on to me your relentless perseverance and strong desire to
learn and for always being there to support me in my endeavors.
朋友和父母很重要,
Rewinding to the origin of this book, I want to thank Andrew Glover for introducing
me to Jennifer Aloi from IBM developerWorks, who in turn launched my technical
writing career by sponsoring the Seamless JSF series. Much of the credit for that series’
success goes to Athen O’Shea for doing a superb job of editing and helping me find
the right words. Little did I know that I would soon be buried deep in turning those
ideas into a book.
项目很重要
I want to thank Marjan Bace and Michael Stephens for taking a chance on me and
trusting that I would finish as I blew past one deadline after the next. Something tells
me they had the real schedule hidden in a drawer and had already anticipated the 15
months that would elapse over the course of this project. I’m also grateful to Andy Kapit
and Andrew Van Etten of CodeRyte, Inc., for endorsing this book in its early stages.
信任很重要
Moving along chronologically, I’d like to acknowledge Cynthia Kane for helping
me see the big picture and for reminding me that I had a book to write when I started
to daydream. I was fortunate to have an ambitious and talented set of reviewers who
donated their time and insight to help make this the best Seam resource available:
Peter Johnson, Doug Warren, Peter Pavlovich, Devon Hillard, Nikolaos Kaintantzis,
Hung Tang, Michael Smolyak, Benjamin Muschko, Kevin Galligan, Judy Guglielmin,
Valentin Crettaz, Carol McDonald, Ara Abrahamian, Horaci Macias, Norman Richards,
Ted Goddard, Costantino Cerbo, Mark Eagle, Carlo Bottiglieri, and Jord Sonneveld.
Thanks to Karen Tegtmeyer for seeking out the reviewers, conducting the
reviews, and scaring the volunteers into actually sending back their comments. Special
thanks to Benjamin Muschko, Pete Pavlovich, and Ray Van Eperen for thoroughly
reading the book and giving me line-by-line edits and advice;
thanks to Michael
Youngstrom for reviewing chapter 15;
thanks to Ted Goddard and Judy Guglielmin for
their help with chapter 12 and the development of the source code for the ICEfaces
example;
and thanks to Valerie Griffin and Daniel Hinojosa for providing last-minute
corrections and feedback. I also want to thank all my loyal MEAP readers and forum
participants, especially those who were there from the very beginning, patiently waiting
for this book to materialize into print.
贵人很重要
The heroes of this project are the production team, under the leadership of Mary
Piergies, who coaxed me out of rewriting hell and worked in overdrive to get this book
into print. The person who took on the biggest burden in this transition was Liz
Welch, my copy editor. I want to extend enormous thanks to Liz for weeding out all
the inconsistencies in the book and tolerating my pursuit of perfection. I also want to
thank Norman Richards, my technical editor, for challenging me to get all my facts
about Seam straight and steering me away from giving readers impractical advice. I’d
like to recognize the tremendous work done by the remaining members of the production
and postproduction team: Katie Tennant for proofreading the manuscript,
squashing all of those “writing bugs”;
Dottie Marsico and Gordan Salinovic for morphing
the chapters from office document format into the professional layout that you
see in front of you in record time;
Leslie Haimes for making the book look eye-catching
on the shelves and enticing readers, like yourself, to dive into it;
Tiffany Taylor for
maintaining the document templates;
Gabriel Dobrescu for handling the book’s web
presence on manning.com;
and Steven Hong for continued support in publicizing
the book and preparing marketing materials.
组织和领导很重要
Join me in thanking Gavin King for sharing his vision of Seam and its contextual
component model with the world as an open source project and to all the Seam developers
that matured his vision into the robust integration framework that it is today.
领袖很重要(先进的思想很重要)
I would like to thank Panera Bread in Laurel, MD, for serving as my retreat/second
office when my house was trying to stifle my writing. I am grateful for the bottomless
tea and free wireless internet. I wish more companies were as progressive as yours.
物质很重要
I’m happy to say that each and every person mentioned in this passage, and sadly
those I overlooked, helped me complete the most ambitious goal of my life. Thanks
again to my wife for standing by me during this project.
被遗漏的不是不重要
========
about this book
If you’re ready to become an expert on Seam, I can guarantee you that this book will
get you there. I don’t use terms that confuse you just to make myself feel smart. I don’t
say “trust me on this;
it will all work out.” I don’t distract you with an outline of the
next chapter when you’re trying to focus on the current material. And especially, I
don’t sprinkle @In and @Out annotations over a class and expect that you’ll know what
they will do. Nope. I lay down the facts. I show you the steps. I reveal the logic. I diagram
the flow. What I like most about programming is that each thing happens for a
reason. The exciting challenge is learning what that reason is and then turning
around and discovering how to make practical use of it. Some areas of Seam are hard
to get, I’ll admit. But trust that with guidance, you will get it. Never settle for less than
the facts, and don’t give up!
通过这本书你足以成为一个SEAM的专家。我不是告诉你那些是什么,而是要告诉你为什么。每个事发生总是有理由的。让人兴奋的就是查出为什么及加以利用。我得承认SEAM的一些地方有些绕,但不放弃,她就是你的。
Not only do I teach you how Seam works, I also teach you the how and the why so
you can go off and teach Seam to others. I’ve traveled into each and every corner of
Seam, and I want to share with you what I’ve experienced to motivate you to travel
there yourself. I want to give you what Seam gave me: the ability to reach my true
potential as a developer. This is the best resource to help you understand Seam without
gaps.
我讲得很细,我教了你你就可以去教别人了。
Roadmap
The goal of this book is to get you started with Seam quickly. It’s divided into four
parts. The first part does a flyover of Seam and gets you ready to learn about it. The
second part focuses in on the core concepts until you can see the blades of grass. The
third part studies Seam’s state-management solution and Java persistence support.
The last part teaches you to make your application secure and stand above the competition.
Best of all, you get to have fun.
本书的目标就是让你快速上手。
书分四部:
一、总貌
二、核心概念
三、状态管理 及JAVA存储支持
四、安全
Chapter 1 answers three questions: What is Seam? Why was Seam created? What does a
Seam application look like? The chapter explains how Seam fits into the Java EE landscape
and enumerates ways it extends the platform to make it more accessible and pertinent.
You see a basic Seam application, which provides an overview of what is to come.
第一章、是什么,为什么,长什么样儿?
Rather than diving directly into the fundamentals of Seam, chapter 2 steps you
through setting up a Seam project. Not only does this give you an environment for
testing the Seam concepts covered in the remainder of the book, it leaves you with a
complete CRUD application that supports incremental hot deployment of changes.
第二章、建立个项目
Because JSF is the primary view framework in Seam, chapter 3 provides a glimpse
of it, identifies its weaknesses, and shows how Seam improves it. You study the pageoriented
enhancements to JSF that Seam provides and get a high-level overview of how
Seam involves itself in the JSF life cycle. By the chapter’s end, you should appreciate
that the only reasonable way to develop using JSF is with Seam.
第三章、JSF
Chapter 4 explores the heart of Seam: the contextual container. You learn what a
Seam component is, how it differs from a component instance, the palette of scopes
in which you can store instances and other context variables, and how Seam manages
the component life cycle. You get a feel for using annotations to control the application.
You also learn ways to access components and when they are instantiated.
第四章、上下文容器
Seam’s central switchboard, the component descriptor, is introduced in chapter 5.
You learn about its two main functions: defining a component in XML as an alternative
to annotations and assigning initial property values, either to control the behavior
of a component or to build object prototypes. Although the metadata in this file is
XML, Seam leverages namespaces to make the configuration type-safe. You even learn
to develop your own namespace. Tucked away at the end of the chapter is an introduction
to Seam’s simple, yet powerful, approach to managing message bundles.
第五章、部件描述符
Chapter 6 is paramount because it presents Seam’s most compelling and progressive
feature, bijection. The key benefit bijection provides is to allow component
instances in different scopes to safely collaborate without risk of scope impedance or
concurrency violations. The other theme in this chapter is how Seam initializes
objects on demand.
第六章、双向注入
Chapter 7 covers Seam’s conversation, another vital feature. Java-based web applications
have always lacked a scope that correlates with the user’s activity. You discover
that the conversation fits this need, overcomes the shortcomings of the HTTP session,
and provides a way for the user to manage parallel activities. The most important use
of the conversation is to manage the persistence context.
第七章、会话
To appreciate how Seam improves Java persistence, you have to learn what it is.
Chapter 8 gives you an introductory view of Java persistence and points you to valuable
resources on the topic;
explains how Java persistence is managed in a pure Java
EE environment;
and helps you distinguish between Hibernate and JPA.
第八章、存储
Chapter 9 presents Java persistence under the stewardship of Seam and demonstrates
how Seam gets persistence right, where Java EE falls short. You learn that the
conversation-scoped persistence context frees you from lazy initialization errors and
dirty merge operations. You also learn that Seam blankets the request in a series of
transactions, extending the guarantees they provide to all operations in a request. The
chapter concludes by examining the most important feature of a multiuser web application:
the application transaction, which makes persistence operations in a conversation
atomic.
第九章、应用级事务
Chapter 10 is round two of developing a CRUD application—only this time, you do
everything yourself. Well, not everything. You learn how to leverage the classes in the
Seam Application Framework to handle most of the boilerplate code, so all you have to
do is design and customize the user interface. After reading chapter 2 and chapter 10,
you should be able to do CRUD in your sleep.
第十章,CRUD
An application wouldn’t be much use without security. In three strokes, chapter 11
gets you authenticating users and then proceeds to teach you how to implement basic
role-based and contextual rule-based authorization to protect your application in powerful
ways.
第十一章、权限控制
One of the things Seam does well is make other technologies look good. In chapter
12, you learn how to add Ajax to your application using RichFaces or ICEfaces components
without touching a line of JavaScript. Seam manages state to ensure these
Ajax interactions don’t bog down the server resources. You also learn to enhance the
capabilities of JavaScript by giving it direct access to server-side components and learn
to integrate Seam with a rich user interface technology such as GWT.
第十二章、AJAX相关
Chapter 13 lets you escape the humdrum of HTML by teaching you to create a wide
variety of content types, such as PDFs, emails, charts, graphics, and binary documents.
You also learn to style your application and give the user control over the user interface.
第十三章、其它文本类型
I had so much to talk about that the last two chapters wouldn’t fit in the book. On
this book’s website (www.manning.com/SeaminAction), you can check out Seam’s
business process management solution in chapter 14 and Seam’s Spring integration in
chapter 15.
第十四、十五章,在网站上
Appendix A shows you how to set up Seam and the supporting environment and
prepares you to follow along with the source code for this book.
Who should read this book?
Seam in Action was described by one reviewer as “written by an expert for experts.” If
you’ve picked up this book hoping it has the breadth of knowledge you seek, that quote
should satisfy you. A second reviewer claimed that “experienced Seam developers are
likely to get something out of reading the book.” Another stated that “even if you are
already an expert in the underlying technologies, you will not be disappointed.” If you
want to master Seam, it’s well worth having this book in your backpack.
谁应读本书
Seam in Action被一个评论人描述成”一个专家写成,多个专家分享”,如果你是想扩展一下你的知识领域,那就来吧。另一个评论人说“有经验的SEAM开发者只用读,就可以长功力”,还有一个评论说“即使你已是底层技术的专家,你也能学到点儿什么的”。如果你想掌握SEAM,包包里的确应有这么一本书。
Where does that leave the rest of you, who are just getting started with Seam? You
won’t be disappointed either. If you’re a Seam newbie or a manager, you’ll get plenty of
value out of just the first two chapters. If you want to go further, you have to ask yourself
if you’re committed to learning about this technology and if you’re willing to put some
effort into it. Are you ready to become an expert? If not, it might be best for you to start
with the Seam reference documentation or perhaps an introductory book. Chances
are, you’ll be back when you’re ready to know all the details about how Seam works.
初学者,你也不会失望。如果你是新手或是搞管理的,前两章就可以让你出去吹吹了。如果想学更多,则要先看看自己有多少毅力了。如果不想成为专家的话,看看参考手册及其它入门书就得了。如果你从那些资料中了解足够多了并真想成为专家的话,我相信你会回来了。
If you’re still with me, be aware that you need some prior experience before you
take on this book. I’ve been able to go into detail in the book because I’ve left out
introductory material that’s readily available elsewhere. At the very least, I expect that
you have experience developing with Java, using the Java Servlet API, and deploying to
application servers or servlet containers. I move quickly through JSF and ORM technologies,
assuming that you’ve at least read about them. You should also have some awareness
of method interceptors and how they work, although this knowledge can be
inferred from the text. Finally, if you’re interested in the parts of the book that cover
the EJB 3 integration or Spring integration, you need some prior experience with these
technologies. That sounds like a lot of prerequisites, but if you’re dedicated, you can
pick up this information from the book and the resources I recommend as you read.
关于预备知识,我希望你以前用Java Servlet API开发过,部署过application servers or servlet containers。在JSF and ORM技术,我会很快跳过。method interceptors你得知道是怎么工作的,如果你对EJB 3 integration or Spring integration感兴趣,则要有些这方面的经验。看上去需要不少预备知识哦,顺着书往下读,我会给出相关资源的链接。
If you’re worried about the requirement to understand JSF, the next section provides
a brief introduction that should get you by. I also suggest a couple of additional
resources if you feel you need more explanation. Honestly, though, basic JSF is
straightforward, and Seam hides a lot of complexity beyond that point.
不用担心你不懂JSF,下一段俺就先给你简单讲讲。
What you need to know about JSF to use Seam
JSF is a component-oriented user interface (UI) framework as opposed to an actionbased
framework like Struts. Struts requires that you write a custom action handler
that processes the request and then forwards control to a JSP page, which renders the
HTML response. JSF, on the other hand, resolves a view template—typically a JSP
page—automatically from a request and transfers control directly to it. The lack of a
front controller may appear to be a step backward. The enhancement comes in the
way the view template is processed.
JSF是面向部件的UI框架(相对于基于动作的框架如Struts提出的),Struts要你写action处理器来处理用户请求并跳转到一JSP页,JSF则使用一个view模板(也常是JSP)自动地让其与请求交互。没有前端控制器好像是一种倒退,但我们有view模板。
JSF reads the view template, which contains custom JSP or Facelets tags, and constructs
a UI component tree, effectively deferring the rendering process. The UI component
tree is a hierarchical graph of Java objects that represents the structure of the
page. Rendering is only a secondary concern and occurs when the component tree is
“encoded” to the client (that is, the browser). The renderer attached to each component
produces the markup.
JSF解析view模板,其中有JSP及Facelets标签,去构建UI部件树,推延了一下重画。UI部件树是分层图形式的JAVA对象,代表一个页面。重画只是我的一种叫法,就是部件树编码后发给客户端的浏览器。每个部件有各自的生成器负责打扮。
The main concern of the UI component tree is to act as a server-side representation
of the view and listen for events that occur in the UI. There is a one-to-one mapping
between the elements in the component tree and the elements on the page (with
the exception of literal HTML). For instance, if the page contains a form with inputs
and buttons, a corresponding form and nested input and button components exist in
the UI component tree. Because the processing of the view template is separate from
the encoding of the UI component tree, you can build the component tree using an
alternate view technology, such as Facelets or pure Java. The component tree can also
produce markup other than HTML.
UI部件树的概念就像服务器端的页面的代表,监听UI事件。部件树与页面一一对应,也就是说页面上有表单,录入框及按钮,部件树上就会有这几个部件。因为view模板的处理是与编码UI部件树分开的,你可以用多个技术来实现部件树,如Facelets or pure Java。
The design of JSF goes beyond separating the view definition and view rendering
with an intermediary object graph. JSF uses the component tree to capture events and
allow programmatic, server-side manipulation of the view. In this regard, it’s similar to
Swing, except that it operates in the context of the web environment. Any event performed
by the user results in an HTTP request. During this request, or postback, the
component tree is “restored” from its previous state. The events are processed, and
the component tree is once again encoded to the client (the HTML response).
JSF用部件树来获得事件并让服务器端来操纵view,从这来看,有些像Swing,只是其操作的是web环境的上下文。任何用户产生的事件都是HTTP请求,在这个请求期间(postback),部件树恢复到其前一个状态。事件处理后,部件树又编码给了客户(HTML response)。
A simple example of the event mechanism is when the user clicks a button—a
UICommand component—in a JSF form. As a result, the method bound to the action of
the button is executed. You don’t have to worry about how the request is handled or
how this mapping is prepared. If the form has inputs—UIInput components—the values
in those inputs are assigned to the JavaBean properties to which they’re bound.
The properties are then available to the action method when it executes. The objects
that are bound to UI components are called managed beans. As you learn later, JSF does
the managing.
一个简单的事件机制的例子是当用户在JSF表单中点了按钮(UICommand 部件)后,绑定的方法会执行。你不用管请求是怎么处理的及该做什么映射。如果用录入框(UIInput部件),则值会赋给其绑定的JavaBean属性,与UI部件绑定了的叫被管理的beans(managed beans),后面会知道是JSF在管理。
How is a managed bean bound to a UI component? This binding is done using
expression language (EL) notation, also found in JSP. There are both value- and
method-binding expressions, although the latter are unique to JSF. JSF can use a value
expression to capture a property value, in addition to outputting it, unlike in JSP. A
method expression is used to bind a method to a UI component so that the method is
invoked when the component is activated.
怎么绑定?是EL表达式(值的或方法的,后者是JSF独有的)。JSF可以用表达式得到属性值,也可以输出它到JSP之类页面。方法表达式则是让UI部件去调用绑定的方法。
In the button example, a method on a managed bean might be bound to the
action of the button through the expression #{beanName.methodName}. This expression
resolves to the methodName() method on an instance of a JSF managed bean
named beanName. Managed beans are defined in the JSF descriptor, faces-config.xml,
using the element. JSF automatically creates instances of these managed
beans as needed.
按钮例子中,#{beanName.methodName}可以调用方法。被管理的beans在JSF描述文件faces-config.xml中用定义,JSF会在需要时自动生成实例。
Value expressions appear identical to method expressions, although they have a
vastly different purpose. The value of an input component might be bound to a property
on a managed bean using the expression #{beanName.propertyName}. JSF reads
the value from the JavaBean getter method, getPropertyName(), when the page is
rendered and writes the new value captured in the input to the setter method, set-
PropertyName(), after the button is clicked. Again, you don’t have to worry about
reading request values from the HttpServletRequest object. The assignment happens
automatically, and you can focus on implementing the business logic.
值表达式与方法表达式类似,#{beanName.propertyName}绑定到属性。JSF用JavaBean的getter方法getPropertyName()来得到值。新值则会用setPropertyName()。同样不用操心从HttpServletRequest对象中得到request请求值。这些是系统自动完成的,你只用去关心业务逻辑。
The EL is an important part of JSF and Seam, and you should be sure to understand
it. Two resources I recommend are the article “Unified Expression Language for JSP and
JSF,” published on java.net,1 and the FAQs about the EL on seamframework.org.2
EL是JSF and Seam的重要部分,两个资源为。。。
The example just presented appears simple enough, but what goes on during each
JSF request, especially the postback, is quite a bit more sophisticated. Each request
activates the JSF life cycle, which consists of six phases:
1 Restore View
2 Apply Request Values
3 Process Validations (and conversions)
4 Update Model Values
5 Invoke Application
6 Render Response
简单的例子在JSF请求尤其是postback中会比较复杂。每个请求会激活一个JSF生命周期。其由六部分组成:
1、存储View(Restore View)
2、解析请求值(Apply Request Values)
3、验证(Process Validations)
4、更新模型值(Update Model Values)
5、调应用(Invoke Application)
6、生成重画的回应(Render Response)
If the request is a postback, the UI component tree is restored during the Restore View
phase. If this is an initial request, meaning the URL was requested from the browser’s
location bar or a regular link, the life cycle skips directly to the Render Response phase.
如果请求是个postback,在Restore View阶段,UI部件树会被存储。如果这是第一次请求(来自浏览器的常规链接),生命周期直接跳到Render Response阶段。
A postback continues through the life cycle. In the three phases that follow Restore
View, the form values are captured, converted, validated, and assigned to the JavaBean
properties on the managed beans to which they are bound. Validations and conversions
get assigned to an input component either as nested tags or correlated with the
property’s type in the JSF descriptor.
postback会经历整个生命周期。在Restore View 后的三个阶段,表单值被得到、转换、校验,赋给JavaBean。校验器和转换器可使用嵌套的标签或在JSF描述文件中作为属性类型的一个性质。
The Invoke Application phase is where the action methods are executed. There can
be at most one primary action and any number of secondary action listeners. The difference
between the two types is that only the primary action can trigger a navigation
rule. The navigation rules, also defined in the JSF descriptor, dictate the next view to
render and are consulted once the Invoke Application phase completes.
Invoke Application phase阶段就是方法执行的阶段。可是是主action及任意数量的次要action监听器。差别就在于主action可以触发导航规则。导航规则也是定义在JSF描述文件中,一旦Invoke Application phase完成,用于跳转到下一页面在。
Finally, in the Render Response phase, the UI component tree is built from the view
template and subsequently encoded to HTML (or alternate output) and sent to the
browser (or client).
最终,Render Response phase阶段,UI部件树编码为HTML之类文本发送到客户浏览器。
That’s all there is to JSF. If you’re a newcomer to the framework, this brief explanation
may leave you wanting. In that case, I’ll point you to several excellent resources
on JSF that should get you up to speed. If you read nothing else, check out the JSF for
nonbelievers series3 on IBM developerWorks. While you’re there, also check out the article
titled “Facelets fits JSF like a glove”4 to learn about Facelets, the alternate view technology
used in Seam applications. If you’re willing to invest in your JSF knowledge,
you should pick up a copy of either JavaServer Faces in Action (Manning, 2004) or Pro
JSF and Ajax (Apress, 2006). When reading these resources, keep in mind that you’re
studying JSF to learn how to use Seam, not necessarily to buy into JSF by itself. In chapter
3, you learn about the many enhancements Seam brings to JSF, a combination that
is sure to please.
一些JSF相关的资源。
Next, because this book makes numerous references to golf, I want to give you
some background to help you understand it as well.
因为本书例子是关于高尔夫的,所以在这里也要说点儿背景知识。
The game of golf
The objective of golf is simple. You must get your ball into a hole in the ground using
the fewest strokes possible, beginning from an area paired with that hole known as a
tee box—or tee for short. A regulation golf course has 18 such holes. Each hole has a par,
which is a guideline for how many strokes you should expect to take to get the ball
into the hole;
this number is significant in calculating your score.
规则很简单,就是用最少的杆数将球入洞。从开球区(tee box简称为tee)开始,打18个洞,每个洞有“标准杆”来暗示你应用几杆来入洞,这个数对你的分值很重要。
The term hole refers to both the hole in the ground and its pairing with a tee box.
A hole has a fixed number of tee boxes, each identified by a color. The tee boxes are
set various distances from the hole and represent different experience levels, to make
the game more challenging for those who are better at it. You pick one color and start
from the designated area for that color on each hole. Those starting points are known
as your tee set. In a golf round, you play each hole in sequence for a given tee set.
开球区设置成了不同的距离表示不同的经验水平,用不同的颜色区分这些级别。
To advance the ball, you use a set of golf clubs. Each golf club consists of a shaft
and a head. The angle of the head determines the loft of the ball when you hit it. The
lower the loft, the further the ball is supposed to go (realizing this difference requires
some skill). To hit the ball, you swing the club much like you would a baseball bat, but
don’t tell the golf pro I said that! You use a special club called a putter to advance the
ball on the green—the area that surrounds the hole. When using the putter, you tap
the ball rather than swing at it. Each time you make contact with the ball, regardless of
which club you use, it counts as one stroke.
球杆。
When you start each hole, you’re permitted to elevate your ball using a golf tee.
The first shot on a hole is the only time you’re allowed to use this aid. The tee is
intended to accommodate the swing of a driver, the club in your bag with the lowest
loft. Once you take your first stroke on a given hole, you advance the ball using a club
until the ball lies at rest in the hole. You then pick up your ball and walk—or ride—to
the next tee. At the end of the round, you add up all your strokes to calculate your raw
score (I won’t get into the concept of a handicap, but just know that it is used to weight
your score.) The lower that number, the better you played.
用杆越少,水平越高。
I chose golf as the topic of the example application because, like programming, it’s
challenging. In golf, you’re only as good as your next round. Sounds a lot like the programming
world, doesn’t it? As soon as we master a technology, there’s one right behind
it to learn. Fortunately, lots of books are available to help us keep on top of our game.
用高尔夫作例子是因为它和编程有相似的地方,就是不断地挑战。
Code conventions
The book provides copious examples, which include all the Seam application artifacts:
Java code, XML-based descriptors, Facelets templates, and Java property files. Source
code in listings or in text is in a fixed-width font like this to separate it from ordinary
text. If there is part of the example I want to draw your attention to, it will be emphasized
using bolded code font. Additionally, Java method names, Java class names, Seam component
names and context variable names, event names, request parameter names, Java
keywords, object properties, EL expressions, Java 5 annotations and enum constants,
XML elements and attributes, and commands in text are also presented using fixedwidth
font. When an annotation appears in the text, the @ symbol is treated as silent.
代码规则
Java, XHTML, and XML can all be verbose. In many cases, the original source code
(available online) has been reformatted;
I’ve added line breaks and reworked indentation
to accommodate the available page space in the book. In some cases, even this
was not enough, and the listings include line-continuation markers (?).
I apply several other space optimizations. Comments in the source code have been
omitted from the listings, and the code is instead described in the text. Class imports
in Java classes also tend to take up a lot of space, so I omit those in cases when the
code editor can easily resolve them for you. The complete set of imports can be found
in the source code. When an implementation of a method isn’t important or remains
unchanged from a previous listing, you will see { ... }, which is a code fold. Often, I
place Java 5 annotations inline with the properties or methods to which they apply to
conserve space. Personally, I prefer to use a newline after each Java 5 annotation in my
own code.
Code annotations accompany some of the source code listings, highlighting
important concepts. In some cases, numbered bullets link to explanations that follow
the listing.
The location of individual applications will be referred to throughout the book
using a variable notion. For instance, the JBoss AS directory is tokenized as
${jboss.home}.
Source code downloads
Seam is an open source project released under the Lesser GNU Public License
(LGPL). Directions for downloading the Seam distribution, which includes both the
source and binaries, are available from the Seam community site, http://seamframework.
org/Download/SeamDownloads.
源码下载
The source code for the Open 18 examples in this book is available from http://
code.google.com/p/seaminaction and released under the LGPL. Because Seam is constantly
evolving, I decided to make the source code available as an open source project
so that I can keep the code up to date for readers as needed. You can also download the
code for the examples in the book from the publisher’s website, http://www.
manning.com/SeaminAction. Details about how to use the source code can be found
in the README.txt file at the root of the source code and also on the project wiki.
Organizing the software
To help you keep the software in order so that you can follow along with the source
code examples, I recommend a directory structure that I adhere to throughout the
book. But it’s just a recommendation. Only you have a say in where your files are
placed, and these conventions are by no means a prerequisite to using Seam.
最后用我建议的目录结构
THE DIRECTORY YOU CALL “HOME”
Your home directory is where your personal files live. The last path in the directory is typically
the same as your username. The book uses the home directory of a fictional
developer, whose username is twoputt, whenever an absolute path must be referenced.
Table 1 shows the home directory for twoputt as it would appear on several different
operating systems. Whenever you see twoputt’s home directory used in the book,
replace it with your own home directory.
称为HOME的目录
The terminal output included in the listings has been generated on a Linux system,
but you can look beyond this detail because it makes no difference which operating
system you use for developing Seam applications.
STRUCTURING YOUR HOME
Table 2 lists several folders, along with their purpose, that I like to set up when doing
development. You’ll recognize these directories from the book’s source code.
HOME中的目录结构
Appendix A shows you how to install the software you need to use the examples in this
book and Seam, with references to this structure.
附录A中有软件安装指导。
About the author
DAN ALLEN is an independent software consultant, author, and open source advocate.
After graduating from Cornell University with a degree in materials science and engineering
in 2000, Dan became captivated by the world of free and open source software,
which is how he got his start in software development. He soon discovered the
combination of Linux and the Java EE platform to be the ideal blend on which to
build his professional career. In his search for a robust web framework, Dan discovered
Seam, which was quickly granted this most coveted spot in his development toolbox.
Excited about Seam, Dan decided to share his thoughts with the world. This
project is a (rather extensive) continuation of his three-part series on Seam published
by IBM developerWorks. Dan continues to write articles on Seam and related technologies.
Dan is a member of the Seam project, an active participant in the Seam community,
and a Java blogger. You can keep up with Dan’s development experiences by
subscribing to his blog at http://mojavelinux.com.
关于作者:
在他希望找到一个强壮的框架时,发现了SEAM。成为了SEAM项目组成员,活跃的SEMA社员。
Author Online
Purchase of Seam in Action includes free access to a private web forum run by Manning
Publications where you can make comments about the book, ask technical questions,
and receive help from the author and from other users. To access the forum and subscribe
to it, point your web browser to http://www.manning.com/SeaminAction. This
page provides information on how to get on the forum once you are registered, what
kind of help is available, and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful dialogue
among individual readers and between readers and the authors can take place.
It is not a commitment to any specific amount of participation on the part of the author,
whose contribution to the AO remains voluntary (and unpaid). We suggest you try asking
the author some challenging questions, lest his interest stray! Since authors are busy
people, like most people in the technology field, there is a chance your question will not
be answered as quickly as you would like. In that case, you are encouraged to try your
question on the Seam community website, http://seamframework.org, where you will
find a much larger pool of people reading and answering Seam-related posts.
The Author Online forum and the archives of previous discussions will be accessible
from the publisher’s website as long as the book is in print.
[@more@]
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/21802202/viewspace-1023248/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/21802202/viewspace-1023248/
推荐阅读
- 做个有目标的女子???---《东京女子图鉴》
- 【9】你有注意到他们嘛()
- 我为什么做没有意义的事
- 关于|关于 SAP UI5 所有控件的共同祖先 - sap.ui.base.ManagedObject
- 如何使用|如何使用 ABAP 代码发送带有 PDF 附件的电子邮件
- 起步的正确姿势???|起步的正确姿势??? ——读《奋斗的正确姿势》有感
- 在这个共享经济的时代,有哪些东西已经实现了共享呢
- 看书对学技术的重要性;前端er工作中应该怎么提升自己;怎样才算是在写有“技术含量”的代码|极客观点
- 君子爱财,取之有道
- 【晨读感悟】快到碗里来,这里有你要的女神修炼大法