JSP personalizzato Taglib: Evaluation nidificati
Domanda
Dire che ho il mio taglib personalizzato:
<%@ taglib uri="http://foo.bar/mytaglib" prefix="mytaglib"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<mytaglib:doSomething>
Test
</mytaglib:doSomething>
All'interno della classe taglib ho bisogno di elaborare un modello e dire al JSP di rivalutare la sua uscita, così per esempio se ho questo:
public class MyTaglib extends SimpleTagSupport {
@Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("<c:out value=\"My enclosed tag\"/>");
getJspBody().invoke(null);
}
}
L'output che ho è:
<c:out value="My enclosed tag"/>
Test
Quando ho davvero bisogno di questo in uscita:
My enclosed tag
Test
E 'questo fattibile? Come?
Grazie.
Soluzione
Tiago, non so come risolvere il tuo esattamente problema, ma si può interpretare il codice JSP da un file. Basta creare un RequestDispatcher e comprendono la 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();
}
Ho provato questo codice in un portlet Liferay, ma credo che dovrebbe funzionare in altri contesti comunque. Se non lo fanno, vorrei sapere:)
HTH
Altri suggerimenti
quello che si ha realmente bisogno di avere è questa:
<mytaglib:doSomething>
<c:out value="My enclosed tag"/>
Test
</mytaglib:doSomething>
e cambiare la tua doTag a qualcosa di simile
@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());
}
}
assicurarsi che il contenuto del corpo jsp è impostato su JSP in TLD:
<bodycontent>JSP</bodycontent>
Perché si scrive un tag JSTL all'interno del vostro metodo di doTag? Il println è direttamente andando in JSP compilato (leggi: servlet). Quando questo viene eseguito il rendering nel browser che verrà stampato in quanto è dal teh browser non capire i tag JSTL
public class MyTaglib extends SimpleTagSupport {
@Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("My enclosed tag");
getJspBody().invoke(null);
}
}
È possibile opzionalmente aggiungere tag HTML per la stringa.