【发布时间】:2011-03-07 02:26:29
【问题描述】:
我有一个使用Velocity 模板和Java 生成HTML 页面的项目。但大部分页面不符合W3C 标准。如何验证这些 HTML 页面并获得一个日志,告诉我哪些页面上有哪些错误/警告?
然后我可以手动修复错误。我已经尝试过 JTidyFilter,但这对我不起作用。
【问题讨论】:
标签: java html validation w3c velocity
我有一个使用Velocity 模板和Java 生成HTML 页面的项目。但大部分页面不符合W3C 标准。如何验证这些 HTML 页面并获得一个日志,告诉我哪些页面上有哪些错误/警告?
然后我可以手动修复错误。我已经尝试过 JTidyFilter,但这对我不起作用。
【问题讨论】:
标签: java html validation w3c velocity
W3C 还提供了一个实验性 API 来帮助自动化验证。他们恳请您限制请求,并提供有关在本地服务器上设置验证器的说明。这肯定是更多的工作,但如果您要生成大量 HTML 页面,那么自动化验证可能也很有意义。
【讨论】:
经过广泛的研究和一点点代码修改,我设法在我的项目中使用了 JTidyFilter,它现在运行良好。 JTidyFilter 在 JTidyServlet 中,它是大约五年前编写的 JTidy 的一个子项目。最近他们更新了代码以符合 Java 5 编译器。我下载了他们的代码,升级了一些依赖项,最重要的是,更改了处理过滤器的 JTidyFilter 类中的一些行,最后让它在我的项目中正常工作。
在重新格式化 HTML 时仍然存在一些问题,因为我在使用 Firefox HTML 验证插件时会看到一两个错误,但大多数页面都通过了验证。
【讨论】:
官方 API 在
自 2007 年起允许通过标记验证器 Web 服务 API 调用本地或远程 W3C 检查器。
有一个使用 Jersey 和 moxy-Jaxb 读取 SOAP 响应的 Java 类解决方案。
这是使用它的 Maven 依赖项:
<dependency>
<groupId>com.bitplan</groupId>
<artifactId>w3cValidator</artifactId>
<version>0.0.2</version>
</dependency>
这里有一个 JUnit 测试供您尝试:
/**
* The URL of the official W3C markup validation service.
* If you'd like to run the tests against your own installation you might want to modify this.
*/
public static final String url = "http://validator.w3.org/check";
/**
* Test the w3cValidator interface with some HTML code
* @throws Exception
*/
@Test
public void testW3CValidator() throws Exception {
String preamble =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\n" +
" \"http://www.w3.org/TR/html4/loose.dtd\">\n" +
"<html>\n" +
" <head>\n" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
" <title>test</title>\n" +
" </head>\n" +
" <body>\n";
String footer = " </body>\n" +
"</html>\n";
String[] htmls = {
preamble +
" <div>\n" +
footer,
"<!DOCTYPE html><html><head><title>test W3CChecker</title></head><body><div></body></html>"
};
int[] expectedErrs = {1, 2};
int[] expectedWarnings = {1, 2};
int index = 0;
System.out.println("Testing " + htmls.length + " html messages via " + url);
for (String html : htmls) {
W3CValidator checkResult = W3CValidator.check(url, html);
List<ValidationError> errlist = checkResult.body.response.errors.errorlist;
List<ValidationWarning> warnlist = checkResult.body.response.warnings.warninglist;
Object first = errlist.get(0);
assertTrue("if first is a string, than moxy is not activated",
first instanceof ValidationError);
//System.out.println(first.getClass().getName());
//System.out.println(first);
System.out.println("Validation result for test " + (index+1) + ":");
for (ValidationError err:errlist) {
System.out.println("\t" + err.toString());
}
for (ValidationWarning warn:warnlist) {
System.out.println("\t" + warn.toString());
}
System.out.println();
assertTrue(errlist.size() >= expectedErrs[index]);
assertTrue(warnlist.size() >= expectedWarnings[index]);
index++;
}
} // testW3CValidator
展示了如何在 Ubuntu Linux 系统上运行您的 on W3C 验证器。
【讨论】:
com.jcabi:jcabi-w3c 似乎更容易并且有效