1. Trang chủ
  2. » Công Nghệ Thông Tin

Mastering omnifaces a problem

664 418 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 664
Dung lượng 4,84 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Mastering OmniFaces Written by: Anghel Leonard and Constantin Alin Reviewed by: Bauke Scholtz and Arjan Tijms... Mastering OmniFaces is a book for any JSF developer.. Constantin Alin is

Trang 2

Mastering OmniFaces

Written by: Anghel Leonard and Constantin Alin Reviewed by: Bauke Scholtz and Arjan Tijms

Trang 4

All trademarks that appear in the book are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark Where such designations appear in this book, they have been printed with initial caps.

The author and publisher of this book have used their best efforts in preparing this book These efforts include the development, research and testing of the theories and computational models given in the book The author and publisher make no warranty of any kind, expressed or implied, with regard to any text, models, program code or algorithms contained in this book The author and publisher shall not be liable in any event for incidental or consequential damages

in connection with, or arising out of, the furnishing, performance, or use of this text, models, program code or algorithms.

ISBN: 978-1-908689-29-0

Trang 5

JavaTM is a registered trademark of Oracle and/or its affiliates

Trang 9

As you will see, however, it is not easy to reach a high level of JSF knowledge Not

Trang 10

everything will be easy to understand and assimilate, and many advanced techniquesrequire hard work, patience, creativity and perseverance Whenever you are really stuck oryou have a brilliant idea of how to improve the OmniFaces project, just contact us using

the information in the Contact/Questions subsection below.

While reading this book, it would be great to also follow the pointed references Thesereferences come from http://omnifaces-fans.org/and they cover different JSF fundamentals thatcouldn’t be covered in the book They are meant to supply mandatory information in order

to understand a specific topic Moreover, the OmniFaces utilities references (also covered

onhttp://omnifaces-fans.org/) are important to understand the OmniFaces shortcuts and toseriously increase your collection of JSF helpers For convenience, we have all thesereferences collected in a ZEEF page available at https://omnifaces-utilities.zeef.com/anghel.leonard

Trang 11

Mastering OmniFaces is a book for any JSF developer From novice to expert, any JSF

developer will find valuable lessons and techniques meant to take JSF projects to a higherlevel of implementation and robustness For newcomers, this book will be a great guidethat will help them to learn JSF in a “healthy” manner and will answer many specificnovice questions For JSF developers, who have previous JSF experience but are lacking

an understanding of best practices and a standard methods of implementing functionality,this book will be like a “gold mine”

Trang 12

Chapter 1 - OmniFaces Components

From this chapter you can collect a set of recipes and techniques for writing a variety ofcustom components You will learn how to write families of components, extend existingcomponents, suppressing/adding specific functionalities, writing custom renderers, etc.Chapter 1 covers:

Trang 13

Param support aConverter to convert the supplied

of implementing validators Amongst other things, you will see how to write a messageinterpolator, and how to implement cross-field validators, which are not supported bydefault in JSF Chapter 2 covers:

Trang 14

validateAllOrNone validates if ALL/NONE UIInputs have

been filled out

validateEqual validates if ALLUIInputs have the same

Trang 16

SelectItemsIndexConverter as SelectItemsConverter, but converts based

on the position (index)

ValueChangeConverter convert only when the submitted value

has changed

GenericEnumConverter use in UISelectMany componentswhose

value is been bound to a List<E>propertywhere E is an enum

Trang 17

Chapter 9 - OmniFaces ViewHandlers

Having solid knowledge about JSF view handlers is like having a professional multi-tool,because through a view handler you can handle the processes that involves the currentview, like initializing, restoring, rendering, etc Contrary to its many usages, JSFdevelopers are pretty reserved in writing custom view handlers or they write them for thewrong purposes, like dealing with components OmniFaces provides a really useful andcorrect use case Chapter 9 covers:

Trang 18

PART III - this part presents a brief overview of the OmniFaces artifacts that were not

presented in detail in this book The final words are dedicated to the upcoming JSF 2.3and OmniFaces 3.0 releases

Chapter 10 - There’s more

CDI, Faces Views, Filters, Managed Beans, Render Kits, Scripts, Functions

Trang 20

Beside the book content, we offer you several things that will help you to enjoyOmniFaces, as follows:

Trang 23

Other References

Is very important to understand the JSF fundamentals which represent the “bricks” used

by OmniFaces to build new artifacts Instead of exploring the Internet by yourself (ofcourse, you are free to do so), we tried to help you with a unitary resource of articles and

posts on JSF & OmniFaces Fans blog, at: http://omnifaces-fans.org/.They are all listed on ZEEFpage, https://omnifaces-utilities.zeef.com/anghel.leonard, andmentioned in the book at specific topics.You also may want to check:https://omnifaces.zeef.com/bauke.scholtz.

Trang 25

If you need to contact the book publisher:

info@glasnevinpublishing.com

Trang 28

on the market such as WebServices, JMS, EJB, CDI, JSF (PrimeFaces, OmniFaces andRichFaces frameworks), Struts, Vaadin, Hibernate, and so on.

Constantin Alin is a passionate senior Java developer focused on

developing web/desktop applications using the latest Java technologies.Beside daily work and learning, in the past few years, he has written andpublished articles for Developer.com and DZone communities, andreviewed the Michael Müller book, Web Development with Java and JSF.Beside other technologies, he is a big fan of JSF and related extensions, like PrimeFaces(starting 2015, certified PrimeFaces developer) and OmniFaces Currently, he’s focused ondeveloping RIA/SPA applications by integrating different technologies, like JavaServerFaces, OmniFaces, PrimeFaces, AngularJS, Bootstrap, RESTful, EJB, and JPA His aim is

to become an excellent JavaServer Faces developer and to be an active contributor todedicated JSF communities

Trang 30

Bauke Scholtz has developed HTML form based web applications since

1996 and has worked primarily with JSF since 2006 On the internet he ismore commonly known as “BalusC”, for his blog at balusc.omnifaces.organd currently has over 16K answers on stackoverflow.com Based on themost recurring problems and shortcomings posted by the JSF community

at stackoverflow.com, and personally faced during years of professional JSF development,

he has together with his jdevelopment.nl colleague Arjan Tijms launched the JSF utilitylibrary OmniFaces in June 2012 With OmniFaces, Bauke tries to not only concretelysolve problems, but also to show off how it should be done He is currently working asweb application specialist at ZEEF.com He is married with a fantastic wife and twoawesome children He likes the Caribbean lifestyle and practicing martial arts

on zeef.com He co-founded the OmniFaces project, started a security project calledOmniSecurity and contributes to the Java EE 7 samples project He maintains a Java EEfocussed blog on arjan-tijms.omnifaces.org

Trang 32

Thank you God, because without you nothing is possible

Thank you Bauke and Arjan, for developing OmniFaces and for trusting us to write thisbook It was a real honor and pleasure working with you

Thank you Glasnevin Publishing, for supporting and publishing this book

Trang 37

Theoretical aspects

Starring: label attribute

Typically, when we need to collect some pieces of data from the end user, we try toprovide a nice and friendly form Basically, that means that we need an explicit label, aninput field and an error messages zone As a JSF developer, you can do this by using the

<h:outputLabel> tag (for the explicit label), the <h:inputText> tag (for the input field) andthe <h:message> tag (for “capturing” validation errors) Actually, these three tags work as ateam for rendering a form item, like in the example below (in this case the items representthe end user first name, last name and e-mail):

First Name: Validation Error: Value is required.

Trang 38

The message is visible to the end user thanks to the<h:message>tag, but the highlightedpart,First Name, is the effect of using the labelattribute If we experimentally removethe label attribute, then the message may become:

Problem/Issue

So, the label component should nearly always have the exact same value as thelabelattribute of the component it labels This means that we have a pretty unnecessaryduplication which gives rise to our issue, or rather, our question: why the value of the label

One step further, and the labels will not be hardcoded anymore (e.g “dynamic” labels) -

<h:outputLabel for=“name” value=”#{msg[‘NAME’]}” />

Trang 39

Source code: OutputLabel_1

Trang 40

The process of switching <h:outputLabel>into<o:outputLabel>is very smooth and painless Afteryou replace the prefixhwith prefix o, you just need to remove the existinglabel attributes,like below:

Trang 42

implementsComponentSystemEventListenervia UIComponent,and can override theprocessEvent()method for obtaining control when certain events are emitted by instances of thatcomponent.

System events listeners are stateless, which means that they provide a good opportunityfor initialization tasks, such as the initialization of attributes of a component, which arestateful by default

Trang 43

the source of this event instance is in a tree that has just had its state restored, so it checksfor aPostRestoreStateEvent event (this is the earlier moment when what follows can beaccomplished, because until this moment, the component tree is partially built/restored,

therefore not all components/clientIds are available) ThePostRestoreStateEvent is only fired

on a postback, not during an initial (GET) request This is done since the targetcomponent(e.g <h:inputText>) in practice only needs the label during a postback (e.g forusage in a conversion/validation message)

Trang 44

Use<o:outputLabel>in order to avoid adding the labelattribute in inputs If the value ofthe <h:outputLabel> is different from the value indicated viathelabelattribute of thecorresponding input, then don’t use<o:outputLabel>

Trang 45

setting an attribute value as a literal or as a value expression

Trang 46

in<h:commandButton>and<h:commandLink>tags for sending request parameters to a managedbean, or nested in <h:link> to send request parameters directly between Facelets,with/without involving a managed bean In other words, the <f:param> tag is used nested

in <h:commandButon> and <h:commandLink> tags for sending POST request parameters, ornested in <h:link> to send GET request parameters In both cases (POST and GET), they’reavailable in the managed bean via ExternalContext#getRequestParameterMap() Additionally, in thecase of GET a <f:viewParam> can be used to validate/convert them Moreover,<f:param>isused nested in the<h:outputFormat> tag to substitute message parameters

So, you may find<f:param> a handy tool for passing request parameters or formatting text.While this is perfectly true, OmniFaces identifies some gaps which illustrate someimportant drawbacks of using <f:param> Let’s see what these gaps are

Problem/Issue

The first problem occurs when we try to use<f:param> to attach to a request a key-valuepair where the value is not an usual text, and is rather an object For example, it iscommon practice to collect data from the end user and, on the server-side, to store it under

a JPA entity instance (the reasons for doing this are not relevant here) Often, the process

of converting the collected data into an object is the job of a JSF converter Moreover,when we want to render the inserted data back to the user, the JSF converter is responsiblefor converting the object back into simple text (string, number) Generally speaking, think

of any piece of information that is rendered as simple text on screen, but it is storedencapsulated into an object on the server side It is, of course, the converter, which acts as

a translator between the text and the object

Now, imagine that you reach a pointof the application when you need to pass that object as

a request parameter Well, obviously you will not be very satisfied by the result obtainedusing the<f:param> out of the box, since the request parameters values are strings by theirnature, while the object only provides a string representation of its content, which most ofthe time is not very useful in such cases (by defaultthis string representation is what youwill pass) Once you conclude this, you may try to fix the problem by overridingthe toString() method of the POJO class, and, it might work in some cases Anyway, sooner

or later, you will realize that in actual factyour converter is returning the exact value that

Trang 47

you want to place on a request parameter, but,<f:param>doesn’t accept a converter, so youhave to re-think the case! Most probably, you will try to reproduce the same stringreturned by the converter through some EL inside thevalueattribute, by calling theobjectgets methods Of course, depending on converter complexity, this approach will orwill not work, and moreover, it will raise an obvious question: aren’t we breaking downthe DRY principle of software development? Well, this is a gap, isn’t it ?!

On the other hand, in order to render parameterized messages, let’s focus onusing<f:param>inside the <h:outputFormat> We already know that <f:param> is the perfectchoice for feeding the parameterized messages with some strings But, instead of a string ,

we might need to pass a piece of HTML or even a JSF component, which is a pretty trickycase You may think that it might be enough to use an un-escaped <h:outputFormat>and tonest the HTML/JSF code inside the<f:param> tag, or to stuff thevalue attribute with thiscontent Unfortunately, only one of thesecombinations is possible, meaning that you canwrite something like below - the parameter value is set as an HTML link ( <a>tag):

<a href=”/app/faces/dial.xhtml?number=0727890877”>dial</a>

The code will be as follows (ask yourself - who would want to do something like this ?):

Most probably, you will want to write the link using JSF tags (<h:link>), not HTML Well,

if you replace the above HTML code with its JSF counterpart, then it will not workanymore! So, we have found another gap!

Ngày đăng: 12/05/2017, 13:14

TỪ KHÓA LIÊN QUAN