熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

Taglib原理和實現:再論El和JSTL標簽

2013-11-15 11:41:02  來源: JSP教程 

  問題你想和JSTL共同工作比如在用自己的標簽處理一些邏輯之後讓JSTL處理余下的工作
  
  看這個JSP例子
  
  <%
  String name=diego;
  requestsetAttribute(namename);
  %>
  <c:out value=${name}/>
  
  
  許多JSTL標簽支持El表達式所以只要你在自己的標簽內部把值塞進request其他jstl標簽就能使用它們
  
  下面這個例子從request裡面取得對象找到它屬性的值塞到request裡去
  
  package diegoyun;
  
  import javaxservletjspJspException;
  import javaxservletjsptagextTagSupport;
  import monsbeanutilsPropertyUtils;
  import orgapachetaglibsstandardlangsupportExpressionEvaluatorManager;
  
  public class SetVarTag extends TagSupport
  {
  private Object value = null;
  private String property = null;
  private String var = null;
  public void setVar(String var)
  {
  thisvar = var;
  }
  public void setProperty(String property)
  {
  thisproperty = property;
  }
  public void setValue(Object value)throws JspException{
  thisvalue = ExpressionEvaluatorManagerevaluate( value valuetoString() Objectclass this pageContext);
  }
  public int doEndTag() throws JspException{
  Object propertyValue = null;
  try{
  propertyValue = PropertyUtilsgetProperty(value property);
  }
  catch (Exception e) {
  throw new JspException(e);
  }
  pageContextsetAttribute(varpropertyValue);
  return EVAL_PAGE;
  }
  }
  
  編寫TLD
  
  <!SetVarTag
  <tag>
  <name>set</name>
  <tagclass>diegoyunSetVarTag</tagclass>
  <bodycontent>empty</bodycontent>
  <attribute>
  <name>value</name>
  <required>true</required>
  <rtexprvalue>true</rtexprvalue>
  </attribute>
  <attribute>
  <name>property</name>
  <required>false</required>
  <rtexprvalue>false</rtexprvalue>
  </attribute>
  <attribute>
  <name>var</name>
  <required>false</required>
  <rtexprvalue>false</rtexprvalue>
  </attribute>
  </tag>
  
  編寫JSP
  
  <%@ page language=java %>
  <%@ page import=diegoyunvo*%>
  <%@ taglib uri=/WEBINF/tlds/diegotld prefix=diego%>
  <%@ taglib uri=/WEBINF/tlds/ctld prefix=c%>
  <html>
  <body bgcolor=#FFFFFF
  <%
  Man man = new Man();
  mansetName(diego);
  requestsetAttribute(manman);
  %>
  Get value from request and set its property value into request:<br>
  <diego:set value=${man} property=name var=myname/>
  now use OutTag of jstl taglib to get the name:<br>
  value is : <c:out value=${myname} />
  
  </body>
  </html>
  
  運行效果如下
  
  Get value from request and set its property value into request:
  now use OutTag of jstl taglib to get the name:
  value is : diego
  結束語
  和JSTL交互是非常有用的技術在JSTL裡提供了許多完成基本功能的標簽如輸出循環條件選擇等僅在處理自己特定邏輯的時候才實現自己的標簽並提供和jstl交互能大大提高重用性和減少工作量
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19434.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.