问题你想和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交互能大大提高重用性和减少工作量