[英]JSP Custom Taglib: Nested Evaluation
Say I have my custom taglib: 说我有我的自定义taglib:
<%@ taglib uri="http://foo.bar/mytaglib" prefix="mytaglib"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<mytaglib:doSomething>
Test
</mytaglib:doSomething>
Inside the taglib class I need to process a template and tell the JSP to re-evaluate its output, so for example if I have this: 在taglib类中,我需要处理一个模板并告诉JSP重新评估它的输出,例如,如果我有这个:
public class MyTaglib extends SimpleTagSupport {
@Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("<c:out value=\"My enclosed tag\"/>");
getJspBody().invoke(null);
}
}
The output I have is: 我的输出是:
<c:out value="My enclosed tag"/>
Test
When I actually need to output this: 当我真的需要输出这个:
My enclosed tag
Test
Is this feasible? 这可行吗? How? 怎么样?
Thanks. 谢谢。
Tiago, I do not know how to solve your exact problem but you can interpret the JSP code from a file. Tiago,我不知道如何解决您的确切问题,但您可以从文件中解释JSP代码。 Just create a RequestDispatcher and include the JSP: 只需创建一个RequestDispatcher并包含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();
}
I tested this code in a Liferay portlet, but I believe it should work in other contexts anyway. 我在Liferay portlet中测试了这段代码,但我相信它应该适用于其他环境。 If it don't, I would like to know :) 如果没有,我想知道:)
HTH HTH
what you really need to have is this: 你真正需要的是这个:
<mytaglib:doSomething>
<c:out value="My enclosed tag"/>
Test
</mytaglib:doSomething>
and change your doTag to something like this 并将你的doTag更改为这样的东西
@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());
}
}
make sure the jsp body content is set to jsp in the tld: 确保在tld中将jsp body内容设置为jsp:
<bodycontent>JSP</bodycontent>
Why do you write a JSTL tag inside your doTag method? 为什么要在doTag方法中编写JSTL标记? The println is directly going into the compiled JSP (read: servlet) When this gets rendered in the browser it will be printed as it is since teh browser doesn't understand JSTL tags. println直接进入已编译的JSP(读取:servlet)当它在浏览器中呈现时,它将按原样打印,因为浏览器不理解JSTL标记。
public class MyTaglib extends SimpleTagSupport {
@Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("My enclosed tag");
getJspBody().invoke(null);
}
}
You can optionally add HTML tags to the string. 您可以选择将HTML标记添加到字符串中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.