说我有我的自定义taglib:

<%@ taglib uri="http://foo.bar/mytaglib" prefix="mytaglib"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<mytaglib:doSomething>
  Test
</mytaglib:doSomething>

在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);
  }
}

我的输出是:

<c:out value="My enclosed tag"/>
Test

当我实际需要输出以下内容时:

My enclosed tag
Test

这是可行的吗?如何?

谢谢。

有帮助吗?

解决方案

蒂亚戈,我不知道如何解决你的 精确的 问题,但是您可以从文件中解释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();
}

我在Liferay Portlet中测试了此代码,但我相信它应该在其他情况下起作用。如果没有,我想知道:)

Hth

其他提示

您真正需要的是:

<mytaglib:doSomething>
  <c:out value="My enclosed tag"/>
  Test
</mytaglib:doSomething>

并将您的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());
 }
}

确保将JSP主体内容设置为TLD中的JSP:

<bodycontent>JSP</bodycontent>

为什么在dotag方法中写下JSTL标签? println直接进入编译的JSP(读:servlet),当它在浏览器中渲染时,它将被打印,因为它是因为Teh浏览器不了解JSTL标签。

public class MyTaglib extends SimpleTagSupport {
      @Override public void doTag() throws JspException, IOException {
        getJspContext().getOut().println("My enclosed tag");
        getJspBody().invoke(null);
      }
    }

您可以选择将HTML标签添加到字符串。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top