我的自定义标签(处理程序为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

最佳答案

您的代码对我有用(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之间有换行符。确保真实文件中没有文件!

10-08 12:17