程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> Jsp tag file例子以及說明

Jsp tag file例子以及說明

編輯:關於JSP

簡介
Jsp2.0後,實現tag的方式除了taglib(TLD)的方式外,還可以通過定義tag文件來代替taglib類。tag file一般放在/WEB-INF/tags目錄或者其子目錄,需要在jsp文件中指定uri。

例子1 將tag file作為內容直接引入
       firstTagTest.jsp

[java] 
<%@ page contentType="text/html; charset=UTF-8" %> 
<%@ taglib prefix="easy" tagdir="/WEB-INF/tags" %> 
Today is <easy:firstTag/> //包含tag,沒有參數傳遞 


firstTag.tag

[java] 
//直接被firstTagTest.jsp引入編譯為java/class文件 
<%@ tag import="java.util.Date" import="java.text.DateFormat"%> 
<%  一時手賤,把structs-config.xml文件中的一段話刪了,結果老是報錯。
報錯內容:Document is invalid: no grammar found
[html] view plaincopyprint?
<?xml version="1.0" encoding="UTF-8"?> 
<strong><span style="color:#ff0000;"><!DOCTYPE struts-config PUBLIC 
       "-//Apache Software Foundation//DTD Tiles Configuration 1.3//EN" 
       "http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd"></span></strong> 
<struts-config> 
    <form-beans> 
        <form-bean name="helloForm" type="com.mars.demo01.structs01.form.HelloForm" /> 
    </form-beans> 
    <!-- 用於配置ActionForm --> 
    <global-exceptions /><!-- 用於配置全局異常 --> 
    <global-forwards /><!-- 用於配置全局跳轉 --> 
    <action-mappings> 
        <action attribute="helloForm" input="/demo01/demo01_hello.jsp" 
            name="helloForm" path="/demo01/demo01_hello" scope="request" 
            type="com.mars.demo01.structs01.action.HelloAction" cancellable="true"> 
            <forward name="show" path="/demo01/demo01_hello.jsp"></forward> 
        </action> 
 
    </action-mappings> 
    <!-- 用於配置Action --> 
    <message-resources parameter="com.mars.demo01.structs01.ApplicationResources" /> 
</struts-config> 
然後恢復原樣,結果又好了,所以這句話是不能刪的。在網上查了查,發現這是一個定義格式的東東。怎麼弄的這麼麻煩。

  DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG); 
  Date now = new Date(System.currentTimeMillis()); 
  out.println(dateFormat.format(now)); 
%> 

     編譯後的代碼
     firstTag_tag.java

    

[java] 
public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException { 
    javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext; 
    javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest(); 
    javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse(); 
    javax.servlet.http.HttpSession session = _jspx_page_context.getSession(); 
    javax.servlet.ServletContext application = _jspx_page_context.getServletContext(); 
    javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig(); 
    javax.servlet.jsp.JspWriter out = jspContext.getOut(); 
    _jspInit(config); 
    jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext); 
 
    try { 
      out.write('\r'); 
      out.write('\n'); 
 
  DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG); 
  Date now = new Date(System.currentTimeMillis()); 
  out.println(dateFormat.format(now)); 
 
      out.write('\r'); 
      out.write('\n'); 
    } catch( java.lang.Throwable t ) { 
      if( t instanceof javax.servlet.jsp.SkipPageException ) 
          throw (javax.servlet.jsp.SkipPageException) t; 
      if( t instanceof java.io.IOException ) 
          throw (java.io.IOException) t; 
      if( t instanceof java.lang.IllegalStateException ) 
          throw (java.lang.IllegalStateException) t; 
      if( t instanceof javax.servlet.jsp.JspException ) 
          throw (javax.servlet.jsp.JspException) t; 
      throw new javax.servlet.jsp.JspException(t); 
    } finally { 
      jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext()); 
      ((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile(); 
    } 
  } 

firstTagTest_jsp.java


[java] 
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) 
        throws java.io.IOException, javax.servlet.ServletException { 
 
    final javax.servlet.jsp.PageContext pageContext; 
    javax.servlet.http.HttpSession session = null; 
    final javax.servlet.ServletContext application; 
    final javax.servlet.ServletConfig config; 
    javax.servlet.jsp.JspWriter out = null; 
    final java.lang.Object page = this; 
    javax.servlet.jsp.JspWriter _jspx_out = null; 
    javax.servlet.jsp.PageContext _jspx_page_context = null; 
 
 
    try { 
      response.setContentType("text/html; charset=UTF-8"); 
      pageContext = _jspxFactory.getPageContext(this, request, response, 
                  null, true, 8192, true); 
      _jspx_page_context = pageContext; 
      application = pageContext.getServletContext(); 
      config = pageContext.getServletConfig(); 
      session = pageContext.getSession(); 
      out = pageContext.getOut(); 
      _jspx_out = out; 
 
      out.write("\r\n"); 
      out.write("\r\n"); 
      out.write("Today is "); 
      if (_jspx_meth_easy_005ffirstTag_005f0(_jspx_page_context))//調用tag類處理方法 
        return; 
    } catch (java.lang.Throwable t) { 
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){ 
        out = _jspx_out; 
        if (out != null && out.getBufferSize() != 0) 
          try { out.clearBuffer(); } catch (java.io.IOException e) {} 
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); 
      } 
    } finally { 
      _jspxFactory.releasePageContext(_jspx_page_context); 
    } 
  } 
 
  private boolean _jspx_meth_easy_005ffirstTag_005f0(javax.servlet.jsp.PageContext _jspx_page_context) 
          throws java.lang.Throwable { 
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context; 
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); 
    //  easy:firstTag 
    org.apache.jsp.tag.web.firstTag_tag _jspx_th_easy_005ffirstTag_005f0 = (new org.apache.jsp.tag.web.firstTag_tag());//構造tag類 
    _jsp_instancemanager.newInstance(_jspx_th_easy_005ffirstTag_005f0); 
    _jspx_th_easy_005ffirstTag_005f0.setJspContext(_jspx_page_context); 
    _jspx_th_easy_005ffirstTag_005f0.doTag();//開始執行dotTag方法,和標准的tag lib類似. 
    _jsp_instancemanager.destroyInstance(_jspx_th_easy_005ffirstTag_005f0); 
    return false; 
  } 

例子2 在jsp引入tag file,並傳遞參數給tag file

encodeTagTest.jsp


[java] 
<%@ page contentType="text/html; charset=UTF-8" %> 
<%@ taglib prefix="easy" tagdir="/WEB-INF/tags" %> 
//引入tag,傳入參數input,值為"<br/> means changing line" 
<easy:encode input="<br/> means changing line"/> 

encode.tag


[java] 
<%@ attribute name="input" required="true" %> 
<%! 
  //定義方法 
  private String encodeHtmlTag(String tag) { 
    if (tag==null) 
      return null; 
    int length = tag.length(); 
    StringBuffer encodedTag = new StringBuffer(2 * length); 
    for (int i=0; i<length; i++) { 
      char c = tag.charAt(i); 
      if (c=='<') 
        encodedTag.append("<"); 
      else if (c=='>') 
        encodedTag.append(">"); 
      else if (c=='&') 
        encodedTag.append("&"); 
      else if (c=='"') 
        encodedTag.append(""");   
      else if (c==' ') 
        encodedTag.append(" "); 
      else 
        encodedTag.append(c); 
 
    } 
    return encodedTag.toString(); 
  } 
%> 
<%=encodeHtmlTag(input)%>//根據傳入的參數input調用方法encodeHtmlTag 

編譯後的代碼

encode_tag.java


[java] 
public final class encode_tag 
    extends javax.servlet.jsp.tagext.SimpleTagSupport 
    implements org.apache.jasper.runtime.JspSourceDependent { 
 
 
 
  private String encodeHtmlTag(String tag) { 
    if (tag==null) 
      return null; 
    int length = tag.length(); 
    StringBuffer encodedTag = new StringBuffer(2 * length); 
    for (int i=0; i<length; i++) { 
      char c = tag.charAt(i); 
      if (c=='<') 
        encodedTag.append("<"); 
      else if (c=='>') 
        encodedTag.append(">"); 
      else if (c=='&') 
        encodedTag.append("&"); 
      else if (c=='"') 
        encodedTag.append(""");   
      else if (c==' ') 
        encodedTag.append(" "); 
      else 
        encodedTag.append(c); 
 
    } 
    return encodedTag.toString(); 
  } 
 
  .... 
  private java.lang.String input; 
 
  public java.lang.String getInput() { 
    return this.input; 
  } 
 
  public void setInput(java.lang.String input) { 
    this.input = input; 
    jspContext.setAttribute("input", input); 
  } 
 
  ...... 
 
  public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException { 
    javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext; 
    javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest(); 
    javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse(); 
    javax.servlet.http.HttpSession session = _jspx_page_context.getSession(); 
    javax.servlet.ServletContext application = _jspx_page_context.getServletContext(); 
    javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig(); 
    javax.servlet.jsp.JspWriter out = jspContext.getOut(); 
    _jspInit(config); 
    jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext); 
    if( getInput() != null )  
      _jspx_page_context.setAttribute("input", getInput()); 
 
    try { 
      out.write('\r'); 
      out.write('\n'); 
      out.write('\r'); 
      out.write('\n'); 
      out.print(encodeHtmlTag(input));//根據傳入參數調用方法 
      out.write("\r\n"); 
      out.write("\r\n"); 
    } catch( java.lang.Throwable t ) { 
      if( t instanceof javax.servlet.jsp.SkipPageException ) 
          throw (javax.servlet.jsp.SkipPageException) t; 
      if( t instanceof java.io.IOException ) 
          throw (java.io.IOException) t; 
      if( t instanceof java.lang.IllegalStateException ) 
          throw (java.lang.IllegalStateException) t; 
      if( t instanceof javax.servlet.jsp.JspException ) 
          throw (javax.servlet.jsp.JspException) t; 
      throw new javax.servlet.jsp.JspException(t); 
    } finally { 
      jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext()); 
      ((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile(); 
    } 
  } 

encodeTagTest_jsp.java


[java]
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) 
      throws java.io.IOException, javax.servlet.ServletException { 
 
  final javax.servlet.jsp.PageContext pageContext; 
  javax.servlet.http.HttpSession session = null; 
  final javax.servlet.ServletContext application; 
  final javax.servlet.ServletConfig config; 
  javax.servlet.jsp.JspWriter out = null; 
  final java.lang.Object page = this; 
  javax.servlet.jsp.JspWriter _jspx_out = null; 
  javax.servlet.jsp.PageContext _jspx_page_context = null; 
 
 
  try { 
    response.setContentType("text/html; charset=UTF-8"); 
    pageContext = _jspxFactory.getPageContext(this, request, response, 
                null, true, 8192, true); 
    _jspx_page_context = pageContext; 
    application = pageContext.getServletContext(); 
    config = pageContext.getServletConfig(); 
    session = pageContext.getSession(); 
    out = pageContext.getOut(); 
    _jspx_out = out; 
 
    out.write("\r\n"); 
    out.write("\r\n"); 
    if (_jspx_meth_easy_005fencode_005f0(_jspx_page_context))//調用處理tag file的方法 
      return; 
  } catch (java.lang.Throwable t) { 
    if (!(t instanceof javax.servlet.jsp.SkipPageException)){ 
      out = _jspx_out; 
      if (out != null && out.getBufferSize() != 0) 
        try { out.clearBuffer(); } catch (java.io.IOException e) {} 
      if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); 
    } 
  } finally { 
    _jspxFactory.releasePageContext(_jspx_page_context); 
  } 

 
private boolean _jspx_meth_easy_005fencode_005f0(javax.servlet.jsp.PageContext _jspx_page_context) 
        throws java.lang.Throwable { 
  javax.servlet.jsp.PageContext pageContext = _jspx_page_context; 
  javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); 
  //  easy:encode 
  org.apache.jsp.tag.web.encode_tag _jspx_th_easy_005fencode_005f0 = (new org.apache.jsp.tag.web.encode_tag()); 
  _jsp_instancemanager.newInstance(_jspx_th_easy_005fencode_005f0); 
  _jspx_th_easy_005fencode_005f0.setJspContext(_jspx_page_context); 
  // /encodeTagTest.jsp(3,0) name = input type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null 
  _jspx_th_easy_005fencode_005f0.setInput("<br/> means changing line");//傳入參數 
  _jspx_th_easy_005fencode_005f0.doTag();//調用doTag方法 
  _jsp_instancemanager.destroyInstance(_jspx_th_easy_005fencode_005f0); 
  return false; 


例子3 在tag file中引入html和tagf文件
includeDemoTagTest.jsp
[java] 
<%@ taglib prefix="easy" tagdir="/WEB-INF/tags" %> 
<easy:includeDemoTag/> 


includeDemoTag.tag

[java]
This tag file shows the use of the include directive.  
The first include directive demonstrates how you can include 
a static resource called included.html. 
<br/> 
Here is the content of included.html: 
<%@ include file="included.html" %> 
<br/> 
<br/> 
The second include directive includes another dynamic resource: included.tagf. 
<br/> 
<%@ include file="included.tagf" %> 
included.tagf
[java] 
<% 
  out.print("Hello from included.tagf"); 
%> 


included.html

[html]
<table> 
<tr> 
  <td><b>Menu</b></td> 
</tr> 
<tr> 
  <td>CDs</td> 
</tr> 
<tr> 
  <td>DVDs</td> 
</tr> 
<tr> 
  <td>Others</td> 
</tr> 
</table> 


編譯後的代碼
includeDemoTag_tag.java
[java] 
public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException { 
   javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext; 
   javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest(); 
   javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse(); 
   javax.servlet.http.HttpSession session = _jspx_page_context.getSession(); 
   javax.servlet.ServletContext application = _jspx_page_context.getServletContext(); 
   javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig(); 
   javax.servlet.jsp.JspWriter out = jspContext.getOut(); 
   _jspInit(config); 
   jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext); 
 
   try { 
     out.write("This tag file shows the use of the include directive. \r\n"); 
     out.write("The first include directive demonstrates how you can include\r\n"); 
     out.write("a static resource called included.html.\r\n"); 
     out.write("<br/>\r\n"); 
     out.write("Here is the content of included.html:\r\n"); 
     out.write("<table>\r\n");//直接把included.html編譯到此類 
     out.write("<tr>\r\n"); 
     out.write("  <td><b>Menu</b></td>\r\n"); 
     out.write("</tr>\r\n"); 
     out.write("<tr>\r\n"); 
     out.write("  <td>CDs</td>\r\n"); 
     out.write("</tr>\r\n"); 
     out.write("<tr>\r\n"); 
     out.write("  <td>DVDs</td>\r\n"); 
     out.write("</tr>\r\n"); 
     out.write("<tr>\r\n"); 
     out.write("  <td>Others</td>\r\n"); 
     out.write("</tr>\r\n"); 
     out.write("</table>"); 
     out.write("\r\n"); 
     out.write("<br/>\r\n"); 
     out.write("<br/>\r\n"); 
     out.write("The second include directive includes another dynamic resource: included.tagf.\r\n"); 
     out.write("<br/>\r\n"); 
 
      out.print("Hello from 
         included.tagf");//直接把included.tagf的內容編譯到此類 
 
     out.write('\r'); 
     out.write('\n'); 
   } catch( java.lang.Throwable t ) { 
     if( t instanceof javax.servlet.jsp.SkipPageException ) 
         throw (javax.servlet.jsp.SkipPageException) t; 
     if( t instanceof java.io.IOException ) 
         throw (java.io.IOException) t; 
     if( t instanceof java.lang.IllegalStateException ) 
         throw (java.lang.IllegalStateException) t; 
     if( t instanceof javax.servlet.jsp.JspException ) 
         throw (javax.servlet.jsp.JspException) t; 
     throw new javax.servlet.jsp.JspException(t); 
   } finally { 
     jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext()); 
     ((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile(); 
   } 
 } 

includeDemoTagTest_jsp.java
 

[java] 
  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) 
        throws java.io.IOException, javax.servlet.ServletException { 
 
 
    final javax.servlet.jsp.PageContext pageContext; 
    javax.servlet.http.HttpSession session = null; 
    final javax.servlet.ServletContext application; 
    final javax.servlet.ServletConfig config; 
    javax.servlet.jsp.JspWriter out = null; 
    final java.lang.Object page = this; 
    javax.servlet.jsp.JspWriter _jspx_out = null; 
    javax.servlet.jsp.PageContext _jspx_page_context = null; 
 
 
 
 
    try { 
      response.setContentType("text/html"); 
      pageContext = _jspxFactory.getPageContext(this, request, response, 
      <span style="white-space:pre">         </span>null, true, 8192, true); 
      _jspx_page_context = pageContext; 
      application = pageContext.getServletContext(); 
      config = pageContext.getServletConfig(); 
      session = pageContext.getSession(); 
      out = pageContext.getOut(); 
      _jspx_out = out; 
 
 
      out.write('\r'); 
      out.write('\n'); 
      if (_jspx_meth_easy_005fincludeDemoTag_005f0(_jspx_page_context))//調用tag file處理方法 
        return; 
    } catch (java.lang.Throwable t) { 
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){ 
        out = _jspx_out; 
        if (out != null && out.getBufferSize() != 0) 
          try { out.clearBuffer(); } catch (java.io.IOException e) {} 
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); 
      } 
    } finally { 
      _jspxFactory.releasePageContext(_jspx_page_context); 
    } 
  } 
 
 
  private boolean _jspx_meth_easy_005fincludeDemoTag_005f0(javax.servlet.jsp.PageContext _jspx_page_context) 
          throws java.lang.Throwable { 
    javax.servlet.jsp.PageContext pageContext = _jspx_page_context; 
    javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); 
    //  easy:includeDemoTag 
    org.apache.jsp.tag.web.includeDemoTag_tag _jspx_th_easy_005fincludeDemoTag_005f0 = (new org.apache.jsp.tag.web.includeDemoTag_tag()); 
    _jsp_instancemanager.newInstance(_jspx_th_easy_005fincludeDemoTag_005f0); 
    _jspx_th_easy_005fincludeDemoTag_005f0.setJspContext(_jspx_page_context); 
    _jspx_th_easy_005fincludeDemoTag_005f0.doTag(); 
    _jsp_instancemanager.destroyInstance(_jspx_th_easy_005fincludeDemoTag_005f0); 
    return false; 
  } 

 

例子4  在jsp頁面中調用tag file中的屬性

invokeTest.jsp

[java]
<%@ taglib prefix="easy" tagdir="/WEB-INF/tags" %> 
<html> 
<head> 
<title>Product Details</title> 
</head> 
<body> 
<easy:invokeDemo> 
  <jsp:attribute name="productDetails"> 
    <table width="220" border="1"> 
    <tr> 
      <td><b>Product Name</b></td> 
      <td>${productName}</td> 
    </tr> 
    <tr> 
      <td><b>Description</b></td> 
      <td>${description}</td> 
    </tr> 
    <tr> 
      <td><b>Price</b></td> 
      <td>${price}</td> 
    </tr> 
    </table> 
  </jsp:attribute> 
</easy:invokeDemo> 
</body> 
</html> 


invokeDemo.tag

[java] 
<%@ attribute name="productDetails" fragment="true" %> 
<%@ variable name-given="productName" %> 
<%@ variable name-given="description" %> 
<%@ variable name-given="price" %> 
<% 
  jspContext.setAttribute("productName", "Pelesonic DVD Player"); 
  jspContext.setAttribute("description",  
    "Dolby Digital output through coaxial digital-audio jack," +  
    " 500 lines horizontal resolution-image digest viewing"); 
  jspContext.setAttribute("price", "65"); 
%> 
<jsp:invoke fragment="productDetails"/>//指明要在dotag()時調用 javax.servlet.jsp.tagext.JspFragment.invoke方法,回調機制 


編譯後的代碼


invokeTest_jsp.java

[java] 
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) 
      throws java.io.IOException, javax.servlet.ServletException { 
 
  final javax.servlet.jsp.PageContext pageContext; 
  javax.servlet.http.HttpSession session = null; 
  final javax.servlet.ServletContext application; 
  final javax.servlet.ServletConfig config; 
  javax.servlet.jsp.JspWriter out = null; 
  final java.lang.Object page = this; 
  javax.servlet.jsp.JspWriter _jspx_out = null; 
  javax.servlet.jsp.PageContext _jspx_page_context = null; 
 
 
  try { 
    response.setContentType("text/html"); 
    pageContext = _jspxFactory.getPageContext(this, request, response, 
                null, true, 8192, true); 
    _jspx_page_context = pageContext; 
    application = pageContext.getServletContext(); 
    config = pageContext.getServletConfig(); 
    session = pageContext.getSession(); 
    out = pageContext.getOut(); 
    _jspx_out = out; 
 
    out.write("\r\n"); 
    out.write("<html>\r\n"); 
    out.write("<head>\r\n"); 
    out.write("<title>Product Details</title>\r\n"); 
    out.write("</head>\r\n"); 
    out.write("<body>\r\n"); 
    //  easy:invokeDemo 
    org.apache.jsp.tag.web.invokeDemo_tag _jspx_th_easy_005finvokeDemo_005f0 = (new org.apache.jsp.tag.web.invokeDemo_tag()); 
    _jsp_instancemanager.newInstance(_jspx_th_easy_005finvokeDemo_005f0); 
    _jspx_th_easy_005finvokeDemo_005f0.setJspContext(_jspx_page_context); 
    javax.servlet.jsp.tagext.JspFragment _jspx_temp0 = new Helper( 0, _jspx_page_context, _jspx_th_easy_005finvokeDemo_005f0, null);// 構造JspFragment類,設置到tag類中,供tag類invoke回調 
    // /invokeTest.jsp(7,0) null 
    _jspx_th_easy_005finvokeDemo_005f0.setProductDetails(_jspx_temp0); 
    _jspx_th_easy_005finvokeDemo_005f0.doTag(); 
    _jsp_instancemanager.destroyInstance(_jspx_th_easy_005finvokeDemo_005f0); 
    out.write("\r\n"); 
    out.write("</body>\r\n"); 
    out.write("</html>"); 
  } catch (java.lang.Throwable t) { 
    if (!(t instanceof javax.servlet.jsp.SkipPageException)){ 
      out = _jspx_out; 
      if (out != null && out.getBufferSize() != 0) 
        try { out.clearBuffer(); } catch (java.io.IOException e) {} 
      if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); 
    } 
  } finally { 
    _jspxFactory.releasePageContext(_jspx_page_context); 
  } 

 
//在jsp類中定義JspFragment類 
private class Helper 
    extends org.apache.jasper.runtime.JspFragmentHelper 

  private javax.servlet.jsp.tagext.JspTag _jspx_parent; 
  private int[] _jspx_push_body_count; 
 
  public Helper( int discriminator, javax.servlet.jsp.JspContext jspContext, javax.servlet.jsp.tagext.JspTag _jspx_parent, int[] _jspx_push_body_count ) { 
    super( discriminator, jspContext, _jspx_parent ); 
    this._jspx_parent = _jspx_parent; 
    this._jspx_push_body_count = _jspx_push_body_count; 
  } 
  public void invoke0( javax.servlet.jsp.JspWriter out )  
    throws java.lang.Throwable 
  { 
    out.write("<table width=\"220\" border=\"1\">\r\n"); 
    out.write("    <tr>\r\n"); 
    out.write("      <td><b>Product Name</b></td>\r\n"); 
    out.write("      <td>"); 
    out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${productName}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); 
    out.write("</td>\r\n"); 
    out.write("    </tr>\r\n"); 
    out.write("    <tr>\r\n"); 
    out.write("      <td><b>Description</b></td>\r\n"); 
    out.write("      <td>"); 
    out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${description}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); 
    out.write("</td>\r\n"); 
    out.write("    </tr>\r\n"); 
    out.write("    <tr>\r\n"); 
    out.write("      <td><b>Price</b></td>\r\n"); 
    out.write("      <td>"); 
    out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${price}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null, false)); 
    out.write("</td>\r\n"); 
    out.write("    </tr>\r\n"); 
    out.write("    </table>"); 
    return; 
  } 
  public void invoke( java.io.Writer writer ) 
    throws javax.servlet.jsp.JspException 
  { 
    javax.servlet.jsp.JspWriter out = null; 
    if( writer != null ) { 
      out = this.jspContext.pushBody(writer); 
    } else { 
      out = this.jspContext.getOut(); 
    } 
    try { 
      this.jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,this.jspContext); 
      switch( this.discriminator ) { 
        case 0: 
          invoke0( out ); 
          break; 
      } 
    } 
    catch( java.lang.Throwable e ) { 
      if (e instanceof javax.servlet.jsp.SkipPageException) 
          throw (javax.servlet.jsp.SkipPageException) e; 
      throw new javax.servlet.jsp.JspException( e ); 
    } 
    finally { 
      if( writer != null ) { 
        this.jspContext.popBody(); 
      } 
    } 
  } 


invokeDemo_tag.java

[java]  
private javax.servlet.jsp.tagext.JspFragment productDetails; 
 
  public javax.servlet.jsp.tagext.JspFragment getProductDetails() { 
    return this.productDetails; 
  } 
 
  public void setProductDetails(javax.servlet.jsp.tagext.JspFragment productDetails) { 
    this.productDetails = productDetails; 
    jspContext.setAttribute("productDetails", productDetails); 
  } 
 
  public java.util.Map<java.lang.String,java.lang.Long> getDependants() { 
    return _jspx_dependants; 
  } 
 
  ...... 
 
  public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException { 
    javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext; 
    javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest(); 
    javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse(); 
    javax.servlet.http.HttpSession session = _jspx_page_context.getSession(); 
    javax.servlet.ServletContext application = _jspx_page_context.getServletContext(); 
    javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig(); 
    javax.servlet.jsp.JspWriter out = jspContext.getOut(); 
    _jspInit(config); 
    jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext); 
    if( getProductDetails() != null )  
      _jspx_page_context.setAttribute("productDetails", getProductDetails()); 
 
    try { 
      out.write("\r\n"); 
      out.write("\r\n"); 
      out.write("\r\n"); 
      out.write("\r\n"); 
<span style="white-space:pre">  </span>//設置屬性包含的變量 
  jspContext.setAttribute("productName", "Pelesonic DVD Player"); 
  jspContext.setAttribute("description",  
    "Dolby Digital output through coaxial digital-audio jack," +  
    " 500 lines horizontal resolution-image digest viewing"); 
  jspContext.setAttribute("price", "65"); 
 
      out.write('\r'); 
      out.write('\n'); 
      ((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke(); 
      _jspx_sout = null; 
      if (getProductDetails() != null) { 
        getProductDetails().invoke(_jspx_sout);//在dotag中回調invoke方法 
      } 
      jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,getJspContext()); 
      out.write('\r'); 
      out.write('\n'); 
    } catch( java.lang.Throwable t ) { 
      if( t instanceof javax.servlet.jsp.SkipPageException ) 
          throw (javax.servlet.jsp.SkipPageException) t; 
      if( t instanceof java.io.IOException ) 
          throw (java.io.IOException) t; 
      if( t instanceof java.lang.IllegalStateException ) 
          throw (java.lang.IllegalStateException) t; 
      if( t instanceof javax.servlet.jsp.JspException ) 
          throw (javax.servlet.jsp.JspException) t; 
      throw new javax.servlet.jsp.JspException(t); 
    } finally { 
      jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext()); 
      ((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile(); 
    } 
  } 


例子5 將頁面內容傳入tag file 的作為參數.

searchEngine.html
[html]
Please click <a href="main.jsp">here</a>\\訪問此頁面生成header.referer 

main.jsp
[java] 
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> 
Your referer header: 
${header.referer}//從http協議中header獲取referer,上一個http地址(從這裡跳轉到當前的地址) 
<br/> 
<tags:doBodyDemo>   //設置jspFragment為tag helper類 
  ${header.referer}//將header.referer的值通過jspFragment的dotag,在dotag回調invoke(out),放入到jspFragment(tag編譯後的類)指定的變量 
</tags:doBodyDemo> 
<a href="viewReferer.jsp">View</a> the referer as a Session attribute. 

doBodyDemo.tag
[java] 
<jsp:doBody var="referer" 
scope="session"/>//轉換out.tostring保存在session變量referer中 

 

viewReferer.jsp
[java] 
The Referer header of the previous page is 
${sessionScope.referer}//這是session中有referer變量,直接可以展示 


例子6 調用tag file並傳入參數

powerTagTest.jsp
[java] 
//自定義標簽,通過傳入參數調用jspFragment.dotag 
<%@ taglib prefix="easy" tagdir="/WEB-INF/tags" %> 
2^3=<easy:power number="2" power="3"/> 

power.tag
[java]
<%-- Shows how to use attributes in a tag file --%>  
<%@ attribute name="number" required="true" description="base" %> 
<%@ attribute name="power" required="true" description="exponent" %> 
<%=Math.pow(Double.parseDouble(number), 
        Double.parseDouble(power))%>//通過傳入的參數計算 

編譯後的代碼
powerTagTest_jsp.java
[java]
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response) 
      throws java.io.IOException, javax.servlet.ServletException { 
 
  final javax.servlet.jsp.PageContext pageContext; 
  javax.servlet.http.HttpSession session = null; 
  final javax.servlet.ServletContext application; 
  final javax.servlet.ServletConfig config; 
  javax.servlet.jsp.JspWriter out = null; 
  final java.lang.Object page = this; 
  javax.servlet.jsp.JspWriter _jspx_out = null; 
  javax.servlet.jsp.PageContext _jspx_page_context = null; 
 
 
  try { 
    response.setContentType("text/html"); 
    pageContext = _jspxFactory.getPageContext(this, request, response, 
                null, true, 8192, true); 
    _jspx_page_context = pageContext; 
    application = pageContext.getServletContext(); 
    config = pageContext.getServletConfig(); 
    session = pageContext.getSession(); 
    out = pageContext.getOut(); 
    _jspx_out = out; 
 
    out.write("\r\n"); 
    out.write("2^3="); 
    if (_jspx_meth_easy_005fpower_005f0(_jspx_page_context))//調用tag file處理方法 
      return; 
  } catch (java.lang.Throwable t) { 
    if (!(t instanceof javax.servlet.jsp.SkipPageException)){ 
      out = _jspx_out; 
      if (out != null && out.getBufferSize() != 0) 
        try { out.clearBuffer(); } catch (java.io.IOException e) {} 
      if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); 
    } 
  } finally { 
    _jspxFactory.releasePageContext(_jspx_page_context); 
  } 

 
private boolean _jspx_meth_easy_005fpower_005f0(javax.servlet.jsp.PageContext _jspx_page_context) 
        throws java.lang.Throwable { 
  javax.servlet.jsp.PageContext pageContext = _jspx_page_context; 
  javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut(); 
  //  easy:power 
  org.apache.jsp.tag.web.power_tag _jspx_th_easy_005fpower_005f0 = (new org.apache.jsp.tag.web.power_tag()); 
  _jsp_instancemanager.newInstance(_jspx_th_easy_005fpower_005f0); 
  _jspx_th_easy_005fpower_005f0.setJspContext(_jspx_page_context); 
  // /powerTagTest.jsp(2,4) name = number type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null 
  _jspx_th_easy_005fpower_005f0.setNumber("2"); //設置tag參數 
  // /powerTagTest.jsp(2,4) name = power type = java.lang.String reqTime = true required = true fragment = false deferredValue = false expectedTypeName = java.lang.String deferredMethod = false methodSignature = null 
  _jspx_th_easy_005fpower_005f0.setPower("3");//設置tag參數 
 
  _jspx_th_easy_005fpower_005f0.doTag(); 
  _jsp_instancemanager.destroyInstance(_jspx_th_easy_005fpower_005f0); 
  return false; 

power_tag.java
[java]
private java.lang.String number;//根據atrribute生成 
  private java.lang.String power;//根據attribute生成 
 
  public java.lang.String getNumber() { 
    return this.number; 
  } 
 
  public void setNumber(java.lang.String number) { 
    this.number = number; 
    jspContext.setAttribute("number", number); 
  } 
 
  public java.lang.String getPower() { 
    return this.power; 
  } 
 
  public void setPower(java.lang.String power) { 
    this.power = power; 
    jspContext.setAttribute("power", power); 
  } 
 
...... 
 
  public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException { 
    javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext; 
    javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest(); 
    javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse(); 
    javax.servlet.http.HttpSession session = _jspx_page_context.getSession(); 
    javax.servlet.ServletContext application = _jspx_page_context.getServletContext(); 
    javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig(); 
    javax.servlet.jsp.JspWriter out = jspContext.getOut(); 
    _jspInit(config); 
    jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext); 
    if( getNumber() != null )  
      _jspx_page_context.setAttribute("number", getNumber()); 
    if( getPower() != null )  
      _jspx_page_context.setAttribute("power", getPower()); 
 
    try { 
      out.write(" \r\n"); 
      out.write("\r\n"); 
      out.write("\r\n"); 
      out.print(Math.pow(Double.parseDouble(number), Double.parseDouble(power))); 
    } catch( java.lang.Throwable t ) { 
      if( t instanceof javax.servlet.jsp.SkipPageException ) 
          throw (javax.servlet.jsp.SkipPageException) t; 
      if( t instanceof java.io.IOException ) 
          throw (java.io.IOException) t; 
      if( t instanceof java.lang.IllegalStateException ) 
          throw (java.lang.IllegalStateException) t; 
      if( t instanceof javax.servlet.jsp.JspException ) 
          throw (javax.servlet.jsp.JspException) t; 
      throw new javax.servlet.jsp.JspException(t); 
    } finally { 
      jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext()); 
      ((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile(); 
    } 
  } 

例子7 嵌套引入tag file
taglibDemoTest.jsp
[java] 
<%@ taglib prefix="easy" tagdir="/WEB-INF/tags" %> 
<easy:taglibDemo/>//引入tag 

tagliDemo.tag
[java] 
<%@ taglib prefix="simple" tagdir="/WEB-INF/tags" %> 
The server's date: <simple:firstTag>//繼續嵌套引入tag\ 

firstTag.tag
[java]
<%@ tag import="java.util.Date" import="java.text.DateFormat"%> 
<% 
  DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG); 
  Date now = new Date(System.currentTimeMillis()); 
  out.println(dateFormat.format(now)); 
%> 


例子8 調用tag file的變量
varDemoTest.jsp
[java]
<%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %> 
Today's date: 
<br/> 
<tags:varDemo> 
In long format: ${longDate} 
<br/> 
In short format: ${shortDate} 
</tags:varDemo> 

varDemo.tag
[java] 
<%@ tag import="java.util.Date" import="java.text.DateFormat"%> 
<%@ variable name-given="longDate" %> 
<%@ variable name-given="shortDate" %> 
<% 
  Date now = new Date(System.currentTimeMillis()); 
  DateFormat longFormat = DateFormat.getDateInstance(DateFormat.LONG); 
  DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT); 
  jspContext.setAttribute("longDate", longFormat.format(now)); 
  jspContext.setAttribute("shortDate", shortFormat.format(now)); 
%> 
<jsp:doBody/>//說明要讓jsp編譯的java類回調,所以jsp編譯的java類有Helper類封裝JspFragment(即tag編譯後的java類) 


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved