gpt4 book ai didi

java - 自定义标签 - JspWriter.write() 不产生输出

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:25 25 4
gpt4 key购买 nike

我的自定义标记(处理程序是 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> )
  • <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>
  • 在 mytags.tld 中,http://java.sun.com/xml/ns/j2ee/web- 之间似乎有一个换行符。 jsptaglibrary_2_0.xsd 。确保真实文件中没有!

关于java - 自定义标签 - JspWriter.write() 不产生输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20179708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com