I want to create a custom tag library which should extend the existing Spring MVC 3.0 tag library. I want to do this because I want my JSP code to be independent of any framework.
That means, if I want to change from Spring to Struts then I don’t have any need to change anything in JSP pages. I just change my customized tag library which will extend the Struts tag library and all work fine.
You can not extend the whole library, but you can extend all tags from the library and create a new descriptor for them, and then use your own tags instead of the Spring ones.
For example, go to the file named
spring-form.tld. You will see tag descriptors, which contain attributes description and a tag class name.So to have your own tag library, you have to create:
Just search Google for ‘jsp custom tags’. Or take a look at JSP custom tags.
For example, take two classes for the [form] tag from Struts and Spring:
You will have to create something like:
I am posting only code for spring’s form tag.
File my-lib.tld:
You will also have to put the .tld file into the META-INF directory of a JAR file. The JAR file with this taglibrary must be just a JAR file included to your WAR file, otherwise taglibraries will not be detected.
And then include your taglib into the JSP file:
And use it:
You will have to create such a library for Struts also, if you want to switch between them.
The only thing that you will need to remember when doing this is that Spring and Struts have a little bit different tag definitions so Struts have ‘focus’ and Spring doesn’t. I think there may be more differences.
You will have to make your tag to have all attributes from Spring and from Struts, if you really want to switch from one to another. But I don’t really think that it is worth the effort.