1

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

}

练习.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
4

1 回答 1

1

您的代码对我有用(JBoss 7.1.1 - 本质上是用于 Web 部件的 Tomcat)。

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

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

    <jsp-config>
        <taglib>
            <taglib-uri>http://www.ets.com/mytags</taglib-uri>
            <taglib-location>/WEB-INF/tags/mytags.tld</taglib-location>
        </taglib>
    </jsp-config>
    
  • http://java.sun.com/xml/ns/j2ee/web- 在 mytags.tld 中,和 之间似乎有一个换行符jsptaglibrary_2_0.xsd。确保真实文件中没有!
于 2013-11-25T11:16:28.837 回答