Wednesday, October 28, 2015

HTML5 form tags with Struts

Introduction

Struts v1 is quite an old release, and by the time it was released, new HTML 5 tags were not introduced yet. We'll see in this article how it is possible to generate some HTML 5 form tags using Struts, instead of using plain HTML in source JSPs. We won't cover all possible tags, but we'll give some hints to successfully do the work. For these examples, we'll use Struts v1.2.9.

 

What needs to be added

If we have a look at W3C documentation regarding HTML 5 form tags, we can notice a bunch of new attributes for input tags. For these examples, we'll only work with placeholder, autocomplete, autofocus, pattern, and required. The idea here is to create subclasses of existing tags classes, where the subclass will handle additional attributes. We'll then see how to wire new attributes to existing HTML tag generation.

 

Existing tag generation

For this, we'll have to take a look at Struts tags source code, we can see that the function called renderInputElement() is actually generating the tag :
The abstract function prepareOtherAttributes(StringBuffer handlers) is very interesting here, because we'll use it as a hook to add our new HTML 5 specific attributes to tags.

 

Text tag

We will subclass existing TextTag class, add new fields for each attribute we want to handle, getters/setters for these, and implement abstract method prepareOtherAttributes() to generate actual HTML code from new attributes :


Password tag

Password tag and text tags are almost identical, the only difference being the value of the type attribute. What we'll do here is just subclass our new Html5TextTag class, and set the type field to password. If we look above in BaseFieldTag extract, we can see that the type field is used to generate the type HTML attribute.That's it, we're done!


Email tag

Email input tag is a new type of input, introduced in HTML 5. It makes it possible to validate an email before the form is actually submitted. Like the password tag described above, the attributes are similar to the text tag. We'll handle it the same way we did for password tag :

Done!

Wiring changes to JSP

What is required now is pretty standard. We'll add a new tag library descriptor file to reference our new tags. The boring part here is that we have to declare, in addition to our new attributes, all existing attributes from subclassed tags... Anyway, example TLD can be found here.
In JSP, we just need to reference our new TLD file. I used html5: prefix here :

That's it! Now, you have fully functionnal HTML 5 tags, generated using Struts v1 framework :


We only took a few new attributes into account here, and it is possible to add new ones like we did here.

No comments:

Post a Comment