Java for Web Learning Notes (36): Custom Tag (4) Custom tag file __java

Source: Internet
Author: User
Tags sessions ticket tld
directives in the tag file

Tag file and JSP are very similar, there are different, the main difference in directives. JSP's directive has include,taglib and page, but tag has include and taglib, no page, and also provides Tag,tag replaces page in JSP, and provides <tag> in TLD file The configuration function.


Tag directive has the following properties, which are optional: pageencoding : The meaning in the same page that defines the encoding of the tag output. iselignored : The same meaning on the page requires that the EL expression not be computed container, and the default is False. language : With the meaning of page, only Java is currently supported. deferredsyntaxallowedasliteral : The same meaning in page requires container to ignore and not parse the deferred El syntax. trimdirectivewhitespaces : With the meaning in page, trim the spaces around directives. Import : With the meaning of page, Java classes can be introduced, with multiple commas separated. Description , display-name , Small-icon , Large-icon : The definition in the Qualcomm TLD, slightly body-content : is a body-content substitution of tld species, but slightly different, valid values are empty, Scriptless and Tagdependent, there is no JSP, that is, in the tag file does not allow the use of scriptlets and expressions. The default value is Scriptless. dynamic-attributes : The same TLD that indicates whether dynamic properties are allowed, the default is null, and that is, dynamic properties are not supported. If required, set to the El name of all dynamic variables you need to obtain, this El is map<string, string> type, key is the name of the dynamic variable, value is the dynamic variable. Example : with TLD, but it is difficult to set effective settings in directive.

In addition, Derective also has variable and attribute, with the variable and attribute in TLD. Variable has description, Name-given, Name-from-attribute,variable-class, declare, scope properties, with TLD, in addition to the alias, You can define variables in a local variable name to use within the tag file. Attribute attributes are description, name, required, Rtexprvalue, type, fragment, Deferredvalue,deferredvaluetype, Deferredmethod and Deferredmethodsignature, with TLD. a simple HTML template tag

We write a simple tag file, as an HTML template, easy to fill in HTML title, coding and other general content. Create a new/web-inf/tags/template/main.tag file, as follows:

<!--body-content= "scriptless": Because to support HTML body content, do not use empty, also do not choose tagdependent (in the query tag passed SQL Use tagdependent when statement). --> <!--dynamic-attributes: Supports dynamic properties (that is, El), and gets the parameter name Dynamicattributes--> <!--space trim. In the <jsp-config> of web.xml we define the &LT;TRIM-DIRECTIVE-WHITESPACES&GT;TRUE&LT;/TRIM-DIRECTIVE-WHITESPACES&GT; But this has no effect on the tag file, so we need to define it manually in each tag file--> <%@ tag body-content= "Scriptless" dynamic-attributes= Dynamicattributes "trimdirectivewhitespaces=" true "%> <!--property name is HTMLTitle; type (String); the value allows runtime Expression (rtexpvalue=true), that is, allow El or script expressions; required (required=true)--> <%@ attribute name= "HTMLTitle" Java.lang.String "rtexprvalue=" true "required=" true "%> <!-- Because the jsp-conf setting in Web.xml does not affect the tag file, if we define a common introduction in BASE.JSPF, we need to introduce it manually again, of course we can also pass%@ taglib prefix= "C" uri= "http://" "% and so on introduced. --> <%@ include file= "/WEB-INF/JSP/BASE.JSPF"%> <! DOCTYPE Html> <!--Here is an example of a dynamic property added to an existing HTML tag: The C:out provides two features: adding a space before displaying value, ensuring that there are spaces before each property;Scapexml, the parameter name cannot be escapexml-->  

Let's add BASE.JSPF:

<%@ taglib prefix= "C" uri= "Http://"%> <%@ taglib prefix= "FMT" uri= "http://" "%>
<%@ taglib prefix=" FN "uri=" Http:// "%>
<%@ taglib prefix= "template" tagdir= "/web-inf/tags/template"%>

The corresponding in the Web.xml:

      < url-pattern>*.jspf</url-pattern>
      < Scripting-invalid>true</scripting-invalid>
      <include-prelude>/web-inf/jsp/base.jspf</ include-prelude>
      < default-content-type>text/html</default-content-type>
  </ Jsp-config>

Here is a JSP example hello.jsp with this tag. In the example Hello, template! is the content of <jsp:body/>.

<template:main htmltitle= "Template homepage" >
    Hello, template!
Small Example: HTML templates more complex tag file: Main.tag

We will implement a simple and useful HTML template, the most is the title, the left side is the navigation bar, the right is the specific content, the following figure.

Here we define two fragment, corresponding HTML title and navigation bar respectively. Fragment the following definition in the official document HTTP://DOCS.ORACLE.COM/JAVAEE/5/TUTORIAL/DOC/BNAMA.HTML#BNAMR. Simply put, fragment is a set of scripts that can include html,jsp.

(optional) Whether This attribute is a fragment to being evaluated by the tag handler (true) or "a" to be evaluated by th e container before being passed to the tag handler. The If is true:you does not specify the Rtexprvalue attribute. The container fixes, the Rtexprvalue attribute at true. You are not specify the type attribute. The container fixes the type attribute at Javax.servlet.jsp.tagext.JspFragment.Defaults to false.

To display the contents of the fragment:

<jsp:invoke fragment= "Navigationcontent"/>

We rewrite the Main.tag file

<%@ tag body-content= "scriptless" trimdirectivewhitespaces= "true"%> <!--defines two string parameters: HTML title and Body Title--> <%@ attribute name= "HTMLTitle" type= "java.lang.String" rtexprvalue= "true" required= "true"%> <%@ Attribute name= "Bodytitle" type= "java.lang.String" rtexprvalue= "true" required= "true"%> <!-- Defines two fragment parameters: distribution is Headconent (defines header properties) and navigationcontent (defines navigation bar content)--> <%@ attribute name= "Headcontent"
Fragment= "true" required= "false"%> <%@ attribute name= "Navigationcontent" fragment= "true" required= "true"%> <%@ include file= "/WEB-INF/JSP/BASE.JSPF"%> <! DOCTYPE html>  
how to set up Fragment:loggedOut.tag 

For the login interface, there is no navigation bar, in fact navigationcibtebt no substance, we provide loggedout.tag on the basis of Main.tag. Main has four parameters required, in Loggedout.tag, we solidify the two fragment parameters, and the other two string parameters as the new tag parameters. We will focus on setting up the fragment through <jsp:attribute>.

<%@ tag body-content= "scriptless" trimdirectivewhitespaces= "true"%>
<!--defines two string parameters and is passed into the Maintag- ->
<%@ attribute name= "HTMLTitle" type= "java.lang.String" rtexprvalue= "true" required= "true"%>
<%@ attribute Name= "Bodytitle" type= "java.lang.String" rtexprvalue= "true" required= "true"%>
<%@ include File= "/WEB-INF/JSP/BASE.JSPF"%> <template:main htmltitle= "${htmltitle}"
bodytitle= "${bodyTitle}" >
	<!--set headcotent parameters. Fragment are relatively long, may contain JSP code, at this time need to be set through Jsp:attribute. -->
	<jsp:attribute name= "headcontent" >
		<link rel= "stylesheet" href= "<c:url value="/resource /stylesheet/login.css "/>"/>		
	<!--set the navigationcontent parameters, because there is no actual border bar, Therefore, there is no actual value for this parameter-->
	<jsp:attribute name= "navigationcontent"/>
	<!--tag's body as concrete content, need to pass to main The body in the tag. -->
materialized navigation bar: Basic.tag

Main.tag is a generic template that we can materialize into the actual project, including: Mapping Headcontent to Extraheadcontent. Navigationcontent materialized as a generic navigation link plus extranavigationcontent.

In this example, we'll show you if you use other fragment in fragment.

<%@ tag body-content= "scriptless" trimdirectivewhitespaces= "true"%> <!--still use four parameters--> <%@ attribute name= "HTMLTitle" type= "java.lang.String" rtexprvalue= "true" required= "true"%> <%@ attribute name= "Bodytitle" type= " Java.lang.String "rtexprvalue=" true "required=" true "%> <%@ attribute name=" Extraheadcontent "fragment=" true " Required= "false"%> <%@ attribute name= "Extranavigationcontent" fragment= "true" required= "false"%> <%@
	Include file= "/WEB-INF/JSP/BASE.JSPF"%> <template:main htmltitle= "${htmltitle}" bodytitle= "${bodyTitle}" > <!--maps headcontent to extraheadcontent--> <jsp:attribute name= "headcontent" > <jsp:invoke fragment= " Extraheadcontent "/> </jsp:attribute> <!--to materialize navigationcontent as a generic navigation link plus extranavigationcontent. --> <jsp:attribute name= "navigationcontent" > <a href= "<c:url value="/tickets "/>" >List Tickets&
	lt;/a><br/> <a href= "<c:url value=" >	  			<c:param name= "Action" value= "create"/> </c:url> ">create a ticket</a><br/> <a href= "<c:url value="/sessions "/>" >list sessions</a><br/> <a href= "<c:url value="/login? Logout "/>" >log out</a><br/> <jsp:invoke fragment= "extranavigationcontent"/> </jsp:attri bute> <jsp:body> <jsp:dobody/> </jsp:body> </template:main>
using the tag

The user is not logged in or fails to log in, redirects to login.jsp, and gives a failure prompt if the login fails.

<%--@elvariable id= "loginfailed" type= "Java.lang.Boolean"--%> <%@ taglib prefix= "template" tagdir= "
Web-inf/tags/template '%>
<template:loggedout htmltitle= ' log in ' bodytitle= ' log in ' > You
	must log in To access the customer support site.<br/><br/> <c:if test=
	"${loginfailed}" >
		<b>the Username or password you entered are not correct. Please try again.</b>
	<form method= "POST" action= "<c:url value="/login "/>" >
		<input type= "text" name= "Username"/><br/><br/>
		password< br/> <input type= "password" name= "password"/><br/><br/> <input type=
		"Submit" Value= "Log in"/>

In the loginservlet.jsp:

protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException c0/> ... Determine if the user logged in successfully  ...
	if (Login failed) {
		request.setattribute ("loginfailed", true);
		Request.getrequestdispatcher ("/web-inf/jsp/view/login.jsp"). Forward (request, response);		
	else{//Login Success
		Session.setattribute ("username", username);
		Request.changesessionid (); Notice here that, based on security, the SessionID has been modified.
		response.sendredirect (...);

Let's look at an example based on basic tag, ticketform.jsp

<template:basic htmltitle= "Create a Ticket" bodytitle= "Create a Ticket" >
        <form method= "POST" action= " Tickets "enctype=" Multipart/form-data "> <input type=" hidden "name=" "
            Action" value= "create"/>
            <input type= "text" name= "Subject" ><br/><br/>
            <textarea name= "Body" rows= "5" cols= "></textarea><br/><br/> <b>attachments"
            <input type= "file" Name= "File1"/><br/><br/> <input
            " Submit "value="/>

RELATED links: My professional Java for WEB applications related articles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.