Taglib原理和實現 第五章:再論支持El表達式和jstl標籤

第五章:再論支持El表達式和jstl標籤

1。問題:你想和jstl共同工作。比如,在用自己的標籤處理一些邏輯之後,讓jstl處理餘下的工作。

2。看這個jsp例子:
....
<%
String name="diego";
request.setAttribute("name",name);
%>

<c:out value="${name}"/>
......

  許多jstl標籤支持El表達式,所以,只要你在自己的標籤內部把值塞進request,其他jstl標籤就能使用它們

3。下面這個例子,從request裏面取得對象,找到它屬性的值,塞到request裏去。

package diegoyun;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;

public class SetVarTag extends TagSupport
{
 private Object value = null; 
 private String property = null; 
 private String var = null;
 public void setVar(String var)
 {
  this.var = var;
 }
 public void setProperty(String property)
 {
  this.property = property;
 }
 public void setValue(Object value)throws JspException{
     this.value = ExpressionEvaluatorManager.evaluate(
            "value", value.toString(), Object.class, this, pageContext);  
 }
 public int doEndTag() throws JspException{
  Object propertyValue = null;
  try{
   propertyValue = PropertyUtils.getProperty(value, property);
  }
  catch (Exception e) {
   throw new JspException(e);
  }  
  pageContext.setAttribute(var,propertyValue);
  return EVAL_PAGE;
 }
}

編寫tld
<!--SetVarTag-->
 <tag>
  <name>set</name>
  <tag-class>diegoyun.SetVarTag</tag-class>
  <body-content>empty</body-content>
  <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="diegoyun.vo.*"%>
<%@ taglib uri="/WEB-INF/tlds/diego.tld" prefix="diego"%>
<%@ taglib uri="/WEB-INF/tlds/c.tld" prefix="c"%>
<html>
<body bgcolor="#FFFFFF">
<%
Man man = new Man();
man.setName("diego");
request.setAttribute("man",man);
%>
Get value from request and set it's 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 it's property value into request:
now use OutTag of jstl taglib to get the name:
value is : diego

4。結語。和jstl交互是非常有用的技術。在jstl裏提供了許多完成基本功能的標籤,如輸出,循環,條件選擇等。僅在處理自己特定邏輯的時候才實現自己的標籤,並提供和jstl交互,能大大提高重用性和減少工作量

發佈了34 篇原創文章 · 獲贊 0 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章