Today, Budi walks us through a refresher and brief overview of server JSP programming. Today's portion covers JavaServer Pages (JSP), with a thorough overview of JavaBeans and Tags. This excerpt comes from chapter one of JavaServer Faces Programming, by Budi Kurniawan (McGraw-Hill/Osborne, ISBN 0-07-222983-7, 2004).
Using JavaBeans allows you to separate the presentation part of a JSP page from the Java code. However, only three action elements—jsp:useBean, jsp:getProperty, and jsp:setProperty—are available for accessing a bean. Therefore in some situations, we need to resort to using code in a JSP page. In other words, in many cases, JavaBeans do not offer complete separation of presentation and business rule implementation.
Also, JavaBeans are designed with reusability in mind, meaning that using a bean to output HTML tags directly is not recommended. Outputting HTML tags from a bean makes the bean usable only from a certain page.
In recognition of the imperfection of JavaBeans as a solution to separation of presentation and business rule implementation, JSP 1.1 defined a new feature: custom tags that can be used to perform custom actions. For example, the following JSP page uses custom tags:
As you can see, the JSP page above is free from Java code. On the first line, you declare that you are using a custom tag in the JSP page, and on the seventh line, you use the custom tag itself. The result output by the <c:myTag/> tag depends on the Java class associated with the custom tag.
Understanding how to use and develop custom tags is important in developing JSF applications, because, in fact, JSF uses custom tags extensively.
To use custom tags, you must develop a custom tag library. We will examine the process of creating custom tag libraries and using them from JSP pages in detail. But first, we’ll take a look at the differences between JavaBeans and custom tags.
Comparing Custom Tags with JavaBeans
Compared to JavaBeans, custom tags offer some advantages:
Custom tags have access to all the objects available to JSP pages.
Custom tags can be customized using attributes.
However, custom tags have the disadvantage of being slightly harder to build and use than JavaBeans. Sometimes, JavaBeans are preferable because of their reusability. There is no hard-and-fast rule governing whether to use JavaBeans or custom tags. You often need to decide which one to use based on the particular project’s specifications.
Remember: This is part two of the first chapter of JavaServer Faces Programming, by Budi Kurniawan (McGraw-Hill/Osborne, ISBN 0-07-222983). Stay tuned for more chapters of developer books from McGraw-Hill/Osborne. Buy this book!