自定义标记 - JspWriter.write()不生成输出

时间:2013-11-24 19:15:55

标签: java jsp java-ee taglib custom-tags

我的自定义标记(处理程序为printSomething.java,实现Tag)正在运行,但未生成预期输出。我期待看到“标签工作!”,但只显示我的模板文本。我是否滥用了JspWriter?代码和输出如下。

printSomething.java

package webcert.ch08.x0804;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;

public class printSomething implements Tag{

private PageContext pc;
private Tag parent;

public void setPageContext(PageContext pc){
    this.pc = pc;
}
public void setParent(Tag parent){
    this.parent = parent;
}
public Tag getParent(){
    return parent;
}
public int doStartTag(){
    try{
        printMessage();
    }
    catch(IOException ioe){}
    return Tag.SKIP_BODY;
}
public int doEndTag(){
    return Tag.EVAL_PAGE;
}
public void release(){

}
public void printMessage() throws IOException{
    JspWriter out = pc.getOut();
    out.write("<b>The tag works!</b>");
    out.print("<b>The tag works!</b>");
    out.flush();
}

}

practice.jspx

<html xmlns:mytags="http://www.ets.com/mytags"
xmlns:jsp="http://java.sun.com/JSP/Page">

<jsp:output omit-xml-declaration="true"/>
<jsp:directive.page contentType="text/html"/>

<head><title>Practice JSPX</title></head>
  <body>
    BEFORE<br/>
    <mytags:printSomething/><br/>
    AFTER<br/>
  </body>
</html>

的web.xml

<web-app>
  <jsp-config>
    <taglib-uri>http://www.ets.com/mytags</taglib-uri>
    <taglib-location>/WEB-INF/tags/mytags.tld</taglib-location>
  </jsp-config>
</web-app>

mytags.tld

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd" 
version="2.0">

  <tlib-version>1.0</tlib-version>
  <short-name>some tags</short-name>
  <tag>
    <name>printSomething</name>
    <tag-class>webcert.ch08.x0804.PrintSomething</tag-class>
    <body-content>empty</body-content>
  </tag>
</taglib>

输出

BEFORE

AFTER

1 个答案:

答案 0 :(得分:1)

您的代码适合我(JBoss 7.1.1 - 本质上是Web部件的Tomcat)。

一些重要的更改,除非它们是您上面代码中的拼写错误:

  • 标记类名称应为PrintSomething(大写'P'),而不是printSomething(根据Java命名约定,但最重要的是根据mytags.tld: <tag-class>webcert.ch08.x0804.PrintSomething</tag-class>
  • web.xml的<jsp-config>语法错误;应该是:

    <jsp-config>
        <taglib>
            <taglib-uri>http://www.ets.com/mytags</taglib-uri>
            <taglib-location>/WEB-INF/tags/mytags.tld</taglib-location>
        </taglib>
    </jsp-config>
    
  • 在mytags.tld中,似乎在http://java.sun.com/xml/ns/j2ee/web- jsptaglibrary_2_0.xsd之间存在换行符。确保真实文件中没有!