wood burning stoves*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Tutorial on Dynamic Attributes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Tutorial on Dynamic Attributes" Watch "Tutorial on Dynamic Attributes" New topic
Author

Tutorial on Dynamic Attributes

Bryan Basham
author
Ranch Hand

Joined: Apr 30, 2001
Posts: 199
Hello SCWCD forum,

In a separate topic, Satish had noticed that there was a topic (Dynamic Attributes) that didn't make it into the core text of HFS/J. I promised that I would write up a brief tutorial on this topic. And here it is...

Before I start, I want to say that I could not find a way to upload the code example that I will be describing. If you would like my source and WAR file, please send me a private message at b_basham@yahoo.com.

Dynamic attributes is a feature of custom tags that allow the JSP author to include any number of attributes on a tag. The canonical use of this feature is to allow a tag developer to mimic (but augment) standard HTML tags. My example follows this usage. I have developed a custom tag to generate a drop-down list (the <select> tag) that automatically generates the set of <option> tags from an application list object.

The webapp has three views. The Home page (index.html) has a link to a web form. The link is to the URL 'goToForm.do' which executes a servlet that sets up a List of java.awt.Color objects in the session-scope and forwards to the 'form.jsp' page. This is the page that uses the <formTags:select> custom tag which is the focus of this tutorial. The user must type in some text in the text field and select a color from the drop-down list and then submit the form. The form action is 'processForm.do' which executes another servlet that validates the user's input and either returns to the form (if the data fails validation) or forwards to the 'results.jsp' page which merely displays the data.

OK, let's get to the meat of this tutorial. Here is the code for the form.jsp page:



The first line declares the use of my custom tag library. The <formTags:select> tag is my custom tag which generates the HTML <select> tag and its <option> subtags. The set of option is declared by the 'optionsList' attribute which must take a java.util.List object. Here I am using the 'colorList' session-scoped attribute, which was setup by the goToForm.do servlet. Notice also that this custom tag has two HTML-specific attributes: 'name' and 'tabindex'. These attributes must be sent to the rendered page verbatim.

Here is what is rendered:


The next step of this tutorial is to discuss how the <formTags:select> custom tag is declared in the TLD. Here is the relevant chunk of the TLD:



Notice that I have only declared a single attribute 'optionsList'. The <dynamic-attributes>true</dynamic-attributes> element declares that this custom tag may also allow any other attributes that the user enters.

The last piece of the Dynamic Attributes puzzle is the tag handler itself. I choose to implement this as a "Simple" tag, but it could also be done as a "Classic" tag. Let me start with a code skeleton for this tag hanlder:



The <formTags:select> handler is the FormSelectTagHandler class. This class extends SimpleTagSupport and implements the DynamicAttributes. This interface introduces the setDynamicAttribute(uri, localName, value) method which allows the tag handle to store any number of attributes used by the JSP page.

The first method setOptionsList stores the 'optionsList' attribute which is unique to my custom tag (it is not an HTML attribute for the <select> tag). This method must exist because I have declared the 'optionsList' attribute in the TLD.

The second method setDynamicAttribute stores any attributes other than those declared in the TLD. In our form.jsp page, the 'name' and 'tabindex' attributes will be stored in the tag object using this method. The localName parameter is the name of the tag and the value is an Object (usually a String) that was passed in as the value of the attribute. The uri parameter is only used when the JSP is a "JSP Document" (an XML document) which may use multiple namespaces. This is rare (and not on the SCWCD exam) so I will not go into any detail on it; for most purposes you can safely ignore this parameter. The most common implementation of this method is to store the localName and value paratemers in a Map object to be used when the HTML is generated.

The last method doTag is responsible for generating the actual HTML content for this custom tag. There are three tasks for this method. First, it must generate the <select> start tag. This task must include all of the HTML-specific (dynamic) attributes stored in the Map describe above. Second, it must generate the set of <option> tags from the optionsList supplied by the JSP author. Third, it must generate the </select> end tag.

Here is the full code (minus package and import statements) for this tag handler:



OK, that's it. I hope that you enjoyed (and learned) from this tutorial. Sorry if it wasn't very head-firsty, but the limitations of HTML prevents a more graphical view of these concepts.

Cheers,
Bryan
[ July 23, 2006: Message edited by: Bryan Basham ]
Darya Akbari
Ranch Hand

Joined: Aug 21, 2004
Posts: 1855
Hi Bryan,

it's always good to have you here . Thanks for the tutorial and thanks to Sathish who made that ball roll.

Regards,
Darya


SCJP, SCJD, SCWCD, SCBCD
Will Lee
Ranch Hand

Joined: Mar 16, 2005
Posts: 58
Thanks a lot for this tutorial. It helps me.


SCJP 1.4, SCWCD, SCDJWS
B.Sathish
Ranch Hand

Joined: Aug 18, 2005
Posts: 372
Thanks for the tutorial Bryan, that was good
Gouri Bargi
Ranch Hand

Joined: Sep 29, 2002
Posts: 47
Bryan, thanks for the tutorial.

- Gouri
saravanan Paramasivan
Greenhorn

Joined: Sep 14, 2005
Posts: 3
Nice tutorial... Thanks
Bryan Basham
author
Ranch Hand

Joined: Apr 30, 2001
Posts: 199
You are welcome, everyone.

I'm glad that I could help and that you got something out of the tutorial.

Remember, if you want the source files, feel free to email me at b_basham@yahoo.com

Cheers,
Bryan

[ September 14, 2005: Message edited by: Bryan Basham ]
[ July 23, 2006: Message edited by: Bryan Basham ]
Deepti Padiyar
Ranch Hand

Joined: Apr 27, 2006
Posts: 31
Hi Bryan,

Thank you for the tutorial and thank you for writing a really good book. I am currently studyiong for my SCWCD, should probably give it in a few weeks.... I would really appreciate if yo could send me a copy of the source code and WArs for Dynamic Attribute examples. My address is sumita.padiyar@gmail.com.

Thanks,
Sumita.


Regards,<br />Deepti.
Bryan Basham
author
Ranch Hand

Joined: Apr 30, 2001
Posts: 199
Hello everyone,

I appreciate that you have discovered this tutorial, but please understand that this is an old thread (from September of 2005) and I don't often return to view the additional posts. Please forgive me if I don't respond to requests in this thread. However, you are always welcome to email me directly at b_basham@yahoo.com.

Regards,
Bryan
Sreeraj G Harilal
Ranch Hand

Joined: Apr 19, 2006
Posts: 310
Respected Bryan Basham,

I have a doubt i checked the code that you put here.
But in this code i can't find anything that uses the dynamic attributes.
Because if i execute the code, then the result is same with or without dynamic attributes.I think the tag handler class using only static attribute optionList.


Color: <formTags:select name='colorField' optionsList='${sessionScope.colorList}'
tabindex='2' />

Color: <formTags:select optionsList='${sessionScope.colorList}'/>



both are producing same result.

I think this code is not clearly showing any usage of dynamic attributes.


SCJP 5.0<br />SCWCD 1.4<br />Preparing for <b>SCEA</b>.<br /><b>"I prefer an interesting vice to a virtue that bores."</b>
Sayak Banerjee
Ranch Hand

Joined: Nov 28, 2006
Posts: 292
Please go through the annotations....usage is explained

The second method setDynamicAttribute stores any attributes other than those declared in the TLD. In our form.jsp page, the 'name' and 'tabindex' attributes will be stored in the tag object using this method. The localName parameter is the name of the tag and the value is an Object (usually a String) that was passed in as the value of the attribute. The uri parameter is only used when the JSP is a "JSP Document" (an XML document) which may use multiple namespaces. This is rare (and not on the SCWCD exam) so I will not go into any detail on it; for most purposes you can safely ignore this parameter. The most common implementation of this method is to store the localName and value paratemers in a Map object to be used when the HTML is generated.


Turn on, tune in, drop out.
Sreeraj G Harilal
Ranch Hand

Joined: Apr 19, 2006
Posts: 310
Sayak i know the usage of dynamic attribute.
But i told here is that the example is not good enough to show the perfect usage of dynamic attribute.If he put that dynamic attributes in the select option list that will make clear to everyone. Am i right?
Bryan Basham
author
Ranch Hand

Joined: Apr 30, 2001
Posts: 199
Originally posted by Sreeraj G H:
Sayak i know the usage of dynamic attribute.
But i told here is that the example is not good enough to show the perfect usage of dynamic attribute.If he put that dynamic attributes in the select option list that will make clear to everyone. Am i right?


Here is the chunk of code in the FormSelectTagHandler that inserts the dynamic attribues into the open tag:

Sincerely,
Bryan
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9349
    
    2

Bryan,

Thanks for the tutorial!


SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Shashi Prakash
Ranch Hand

Joined: Mar 28, 2007
Posts: 40
Thanks for such a nice tutorial ..It cleared my concept of dynamic atributes ..


Thanks,<br />Target Scwcd<br />SCJP 1.4
khushhal yadav
Ranch Hand

Joined: Jun 20, 2007
Posts: 242

Hi Bryan

I have a doubt.

<formTags:select name='colorField'
optionsList='${sessionScope.colorList}' tabindex='2' />


Is this statement OK.
I think if we have both static and dynamic attributes for a tag, the static attributes need to come first. And here I think name is a dynamic attribute.

And one more question, Can we have EL to set the values for dynamic attributes??

Regards,
Khushhal


rgrds,
Khushhal
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

I think if we have both static and dynamic attributes for a tag, the static attributes need to come first.

May I ask you where you have read this ?

Can we have EL to set the values for dynamic attributes??

Yes, dynamic attributes accept request time expression values.


[My Blog]
All roads lead to JavaRanch
khushhal yadav
Ranch Hand

Joined: Jun 20, 2007
Posts: 242

Hi Christophe

I am agree with your second point.
Yes, dynamic attributes accept request time expression values.

But Look at the code..

My servlet Class FunctionTag.java


package myTags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

public class FunctionTag extends SimpleTagSupport implements DynamicAttributes
{
private double num = 0;
private String output = "";

public void setNum(double num)
{
this.num = num;
}

public void setDynamicAttribute(String uri, String localname, Object value)
{
double val = Double.parseDouble((String)value);

if(localname == "min")
{
output = output + "<tr><td>The minimum of " + num + " and " + val + " </td><td> " + Math.min(num, val) + "</td></tr>";
}
else if(localname == "max")
{
output = output + "<tr><td>The maximum of " + num + " and " + val + " </td><td> " + Math.max(num, val) + "</td></tr>";
}
else if(localname == "pow")
{
output = output + "<tr><td>" + num + " raised to the " + val + " power </td><td>" + Math.pow(num, val) + "</td></tr>";
}
}

public void doTag() throws IOException, JspException
{
getJspContext().getOut().print(output);
}
}


My TLD myFuncs.tld

<?xml version="1.0" encoding="ISO-8859-1"?>

<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3g.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd"
version="2.0">

<tlib-version>1.2</tlib-version>
<tag>
<name>functions</name>
<tag-class>myTags.FunctionTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>num</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<dynamic-attributes>
true
</dynamic-attributes>
</tag>
</taglib>


When my jsp is: function.jsp

<%@ page isELIgnored="false"%>
<%@ taglib prefix="test" uri="http://myFuncs/Functions"%>
<table border="1">
<test:functions num="${3*2}" min="4" max="8" pow="2"/>
</table>


Output Is:

The minimum of 6.0 and 4.0 4.0
The maximum of 6.0 and 8.0 8.0
6.0 raised to the 2.0 power 36.0

It's OK.
----------------------------------------------------------------

Butttt...


When my jsp is: function1.jsp


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page isELIgnored="false"%>
<%@ taglib prefix="test" uri="http://myFuncs/Functions"%>

<c:set var="var2" value="6" scope="request"/>
<table border="1">
var1 = <c ut value="${var2}"/>
<test:functions min="${var2}" num="${3*2}" max="8" pow="2"/>
</table>


Output Is:



var1 = 6
The minimum of 0.0 and 6.0 0.0
The maximum of 6.0 and 8.0 8.0
6.0 raised to the 2.0 power 36.0


Checkout the position for dynamic attribute min

Please explain this

-------------------------------------------------------------------------

One more thing, is there some version compatibilty regarding the use of runtime expressions for dynamic atrributes.???
Or the runtime expressions have been always applicable to dynamic strributes. Please confirm that.

As I have read it somewhere "If you try to use EL to set dynamic attributes, you will get an error".
Not able to recollect the reference.
Whenever come across to that again, will let you know.

Regards,
Khushhal
khushhal yadav
Ranch Hand

Joined: Jun 20, 2007
Posts: 242

Christophe

I want to add one more thing.

Below code is working fine

When my jsp is: function.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page isELIgnored="false"%>
<%@ taglib prefix="test" uri="http://myFuncs/Functions"%>

<c:set var="var2" value="4" scope="request"/>
<table border="1">
var1 = <c ut value="${var2}"/>
<test:functions num="${3*2}" min="${var2}" max="8" pow="2"/>
</table>


Output Is:

var1 = 4
The minimum of 6.0 and 4.0 4.0
The maximum of 6.0 and 8.0 8.0
6.0 raised to the 2.0 power 36.0


It's Ok. Use of EL is OK.
But please reply for my compatibility query.


Regards,
Khushhal
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

It's Ok. Use of EL is OK. But please reply for my compatibility query.

Which container are you using ?
khushhal yadav
Ranch Hand

Joined: Jun 20, 2007
Posts: 242

I am using jakarta-tomcat-5.0.28 as container and IE7 as a browser.

Regards,
Khushhal
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

One more thing, is there some version compatibilty regarding the use of runtime expressions for dynamic atrributes.??? Or the runtime expressions have been always applicable to dynamic strributes. Please confirm that.

I dno't know why I was asking for your container version, and I don't know why you're asking that either. As far as I know, dynamic attributes were introduced in JSP2, so there should not be any problem as long as you're using a container supporting JSP2. Dynamic attributes expect runtime expressions from the beginning.
khushhal yadav
Ranch Hand

Joined: Jun 20, 2007
Posts: 242

Ok Christophe

Actually, I am a novice to all these things.

And somewhere I read "If you try to use EL to set dynamic attributes, you will get an error"
I am sure it's written there. As dynamic attributes don't have <rtexprvalue> option.

That's why I asked.

Regards,
Khushhal
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Ok, I've understood why you were asking Don't worry, dynamic attributes implicitly support runtime expression, no matter what.
khushhal yadav
Ranch Hand

Joined: Jun 20, 2007
Posts: 242

Thank you Christophe

Regards,
Khushhal
Bryan Basham
author
Ranch Hand

Joined: Apr 30, 2001
Posts: 199
Hello Khushhal,

I read through your thread with Christophe and it was not clear to me that one of your questions was answered. You had a question about the code snippet:


which returned:


This result makes sense to me because the 'min' attribute is set first before the 'num' attribute. Therefore, the this.num instance variable is zero and the Math.min of 0 and 6 (from ${var2}) is still 0.

The order that tag attributes are set is based upon the order that the attributes appear in the tag itself.

Make sense?

Cheers,
Bryan
[ August 11, 2007: Message edited by: Bryan Basham ]
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

I thought that khushhal made this out himself after saying that using EL was ok, but thank you for clarifying it.
khushhal yadav
Ranch Hand

Joined: Jun 20, 2007
Posts: 242

Hi Bryan

Nice to have something fom you.
I got your point.
Since we don't have any value for the num by the time val variable is set for min, we get 0 for num, which is the default value for num.

Thanks a lot Bryan
Hope we will keep listening from you in future as well.

Regards,
Khushhal
Sudarshan Sreenivasan
Ranch Hand

Joined: Jun 28, 2007
Posts: 188

for ( String attrName : tagAttributes.keySet() ) {
out.print(attrName);
out.print("='");
out.print(tagAttributes.get(attrName));
out.print('\'');
}



This code is from the tag handler

Does'nt this give a compile time error ???
Carlos Mario Alvarez Palacio
Greenhorn

Joined: Aug 29, 2007
Posts: 2
About the reference of where does it says that dynamic attributes doesn't accept EL, you can see it on the "SCWCD exam study kit, Second Edition" book from manning. The exact quote says using EL on dynamic attributes shows an error, although it works when you try that.
Bryan Basham
author
Ranch Hand

Joined: Apr 30, 2001
Posts: 199
First, to Sid, the code compiles fine. Please send me an email (b_basham@yahoo.com) if you want the actual code.

Next, to Carlos, that study kit is incorrect. All dynamic tags allow EL and JSP expressions.

Cheers,
Bryan
Damodar Mukherjee
Ranch Hand

Joined: Mar 20, 2007
Posts: 135
Originally posted by sid sree:


This code is from the tag handler

Does'nt this give a compile time error ???



I think you are not using j2se 1.5


SCJP 1.5, SCWCD 1.4, Next... SCBCD5
Damodar Mukherjee
Ranch Hand

Joined: Mar 20, 2007
Posts: 135
Thank you so much Bryan for the nice tutorial...
Khadija Lokhandwala
Ranch Hand

Joined: Sep 11, 2007
Posts: 33
Hello everyone,
I went through the tutorial on dynamic attributes. My understanding is that it allows The JSP author to enter attributes while writing a JSP without defining them in a TLD. In your tutorial "name" and "tabindex" were the dynamic attributes which are not defined in the TLD.It means I can add another dynamic attribute "attri" if I want to.

Am I correct.
Please correct me if I am mistaken.

Thanks Bryan for the tutorial.


If you ask me anything I don't know, I'm not going to answer.<br />--Yogi Berra
Bryan Basham
author
Ranch Hand

Joined: Apr 30, 2001
Posts: 199
Hello Khadija,

You are correct. You can add any tag attribute and it will be handled by the setDynamicAttribute() method. Note that no validation is possible that you have typed the attribute name correctly. For example, if you want to add the 'onchange' JavaScript attribute but you mistype it as 'onchnge' then this attribute is passed on to the generated HTML <select> tag. When the browser renders the <select> tag it will not understand the 'onchnge' attribute and will just ignore it.

If you need to validate the attribute names, then you will have to add code to perform this validation in the setDynamicAttribute() method.

HTH,
Bryan
Khadija Lokhandwala
Ranch Hand

Joined: Sep 11, 2007
Posts: 33
Thanks a ton Bryan!!!
Bobby Sharma
Ranch Hand

Joined: Mar 18, 2008
Posts: 574
    
    1

This example was included in HFSJ 1.5 with great explanation.
Can somebody explain the tag logic here?


best regards,
[ May 03, 2008: Message edited by: omi sharma ]

Back to Java , again.
Ha Minh Nam
Greenhorn

Joined: May 22, 2007
Posts: 14

Thanks Bryan for a really easy-to-understand example.


SCJP 5.0 (80%)<br />SCWCD 1.5 (89%)
Harshana Dias
Ranch Hand

Joined: Jun 11, 2007
Posts: 327
Hey,
What if we want to directly see the form.jsp page instead of see index.html. then where we declare colorList ?
Thank You
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Tutorial on Dynamic Attributes