280 likes | 400 Vues
JSP in Action. continuation. JSP’s Tag Extension Mechanism. You can define your own actions to replace lengthy scriptlets By “hiding” functions behind custom tags, you can increase modularity and maintainability of your pages .
E N D
JSP in Action continuation
JSP’s Tag Extension Mechanism • You can define your own actions to replace lengthy scriptlets • By “hiding” functions behind custom tags, • you can increase modularity and maintainability of your pages.
Define Java classes that provide the functionality of the new actions, including the definition of their attributes (e.g., myAttributeName). These classes are called tag handlers. • Provide a formalized description of your action elements, so that Tomcat knows how to handle them. For example, you need to specify which actions can have a body and which attributes can be omitted. Such a description is called a tag library descriptor (TLD). • In the JSP pages, tell Tomcat that the pages need your tag library and specify the prefix that you want to identify those custom tags with.
BodylessCustom Action • <wow:weekday date=“date”/>
Step 1: Define the Tag Handler • A tag handler for a bodyless custom tag is a class that implements the interfaces java.io.Serializable and javax.servlet.jsp.tagext.Tag. • Remember that to satisfy an interface, you have to implement all the methods it defines. • To satisfy Serializable, you only need to define a unique identifier, like this: static final long serialVersionUID = 1L;
Step 1: Define the Tag Handler • Bodied actions need to implement an interface, javax.servlet.jsp.tagex.BodyTag instead of Tag. • Implement doEndTagmethod,anddoAfterBody <wow:weekdayBody></wow:weekdayBody>
Tag Files • Tag files are special JSP files that replace tag handlers written in Java. • There are three directives: tag, attribute, and variable.
The tag directive of a tag file replaces the page directive of a JSP page, and the attributedirective lets you define an input parameter. • Another simplification is in sending the result to the output, because in the tag file the implicit variable out makes it unnecessary to invoke pageContext.getOut().
If you omit the attribute var, doBody sends the body’s result to the output; • If you replace varwith varReader, the result is stored as a java.io.Readerobject instead of a java.lang.String; • If you add the attribute scope, you can specify var/varReaderto be defined as a request, session, or application attribute, instead of in the page scope. • Know that jsp:invoke is very similar to jsp:doBody but operates on a JSP fragment instead of the action body. • For example, by writing the following two lines in a tag file <%@attribute name="fragName" fragment="true"%> <jsp:invoke fragment="fragName"/>