Custom Tags:-
A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.
Advantages of Custom Tags:-
1-Elimenates the need of scriptlate tags which is considered as bad programming approach.
2-Sepeartion of business logic from the jsp so tat it may be easy to maintain.
3-Reusability:-It makes the possibility to make reusability of business logic.
Syntax of Custom Tag:-
There are two ways to use the custom tags:-
1-
2-
Example Of Custom Tag:-
For creating the Custom Tag,We need to follow the following steps:-
1:- Create The tag Handler Class and perform action at the start or at end of tag.
2-Create The tag library descriptor file and define tags
3-Create the JSP file that uses the Custom Tag defined in TLD file.
1:- Create a dynamic project in your IDE(Here I am using Spring Tool Suite™) you can use eclipse or any IDEBut in case of Eclipse you will have to add jsp-api 2.0 jar
The JSP 2.0 specification introduced Simple Tag Handlers for writing these custom tags.
To write a customer tab you can simply extend SimpleTagSupport class and override the doTag() method, where you can place your code to generate content for the tag.
2:- Create The tag Handler Class and perform action at the start or at end of tag--here we create the MyTagHandler.java as given below
3-Now Create tag library file
here we create mytags.tld and put inside the following as mentioned below:-
directory Dyanamic_Project_Name\WebContent\WEB-INF\mytags.tld
4-Create the JSP file that uses the Custom Tag defined in TLD file.Here we create index.jsp and in web.xml set as welcome page as given below
1:-web.xml:-
2:-index.jsp:-
Here prefix I have taken as prefix="Sample" and taglib uri="WEB-INF/mytags.tld"
when I run this dynamic project will get the value what tried to print like here will print Hello Custom Tag.
created custom tag without body content like fashion.
Note:-
Spring Tool Suite™ is an Eclipse-based development environment that is customized for developing Spring applications. It provides a ready-to-use environment to implement, debug, run, and deploy your Spring applications, including integrations for Pivotal tc Server, Pivotal Cloud Foundry, Git, Maven, AspectJ, and comes on top of the latest Eclipse releases.It is freely available for development and internal business operations use with no time limits, fully open-source and licensed under the terms of the Eclipse Public License.
Code by Haakblog
Sunday, 9 February 2014
JSP:Custom Tags
04:09
No comments