問題:你想和JSTL共同工作。比如,在用自己的標簽處理一些邏輯之后,讓JSTL處理余下的工作。
看這個JSP例子:
<% String name="diego"; request.setAttribute("name",name); %> <c:out value="${name}"/> ......
許多JSTL標簽支持El表達式,所以,只要你在自己的標簽內部把值塞進request,其他jstl標簽就能使用它們
下面這個例子,從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
結束語
和JSTL交互是非常有用的技術。在JSTL里提供了許多完成基本功能的標簽,如輸出,循環,條件選擇等。僅在處理自己特定邏輯的時候才實現自己的標簽,并提供和jstl交互,能大大提高重用性和減少工作量。
|