JSP Custom Taglib: evaluación anidada
Pregunta
Digamos que tengo mi taglib personalizado:
<%@ taglib uri="http://foo.bar/mytaglib" prefix="mytaglib"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<mytaglib:doSomething>
Test
</mytaglib:doSomething>
Dentro de la clase Taglib, necesito procesar una plantilla y decirle al JSP que reevalúe su salida, así que, por ejemplo, si tengo esto:
public class MyTaglib extends SimpleTagSupport {
@Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("<c:out value=\"My enclosed tag\"/>");
getJspBody().invoke(null);
}
}
La salida que tengo es:
<c:out value="My enclosed tag"/>
Test
Cuando realmente necesito sacar esto:
My enclosed tag
Test
¿Es esto factible? ¿Cómo?
Gracias.
Solución
Tiago, no sé cómo resolver tu exacto Problema, pero puede interpretar el código JSP desde un archivo. Simplemente cree un requestdispatcher e incluya el JSP:
public int doStartTag() throws JspException {
ServletRequest request = pageContext.getRequest();
ServletResponse response = pageContext.getResponse();
RequestDispatcher disp = request.getRequestDispatcher("/test.jsp");
try {
disp.include(request, response);
} catch (ServletException e) {
throw new JspException(e);
} catch (IOException e) {
throw new JspException(e);
}
return super.doStartTag();
}
Probé este código en un portlet de Liferay, pero creo que debería funcionar en otros contextos de todos modos. Si no es así, me gustaría saber :)
Hth
Otros consejos
Lo que realmente necesitas tener es esto:
<mytaglib:doSomething>
<c:out value="My enclosed tag"/>
Test
</mytaglib:doSomething>
y cambia tu punto a algo como esto
@Override public void doTag() throws JspException, IOException {
try {
BodyContent bc = getBodyContent();
String body = bc.getString();
// do something to the body here.
JspWriter out = bc.getEnclosingWriter();
if(body != null) {
out.print(buff.toString());
}
} catch(IOException ioe) {
throw new JspException("Error: "+ioe.getMessage());
}
}
Asegúrese de que el contenido del cuerpo JSP esté configurado en JSP en el TLD:
<bodycontent>JSP</bodycontent>
¿Por qué escribes una etiqueta JSTL dentro de tu método DOTAG? El println va directamente al JSP compilado (léase: servlet) cuando esto se representa en el navegador, se imprimirá como está ya que el navegador no comprende las etiquetas JSTL.
public class MyTaglib extends SimpleTagSupport {
@Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("My enclosed tag");
getJspBody().invoke(null);
}
}
Opcionalmente, puede agregar etiquetas HTML a la cadena.