【发布时间】:2010-09-17 13:09:21
【问题描述】:
如何从 jsp 页面的输出中去除多余的空格?有没有可以在我的 web.xml 上翻转的开关?有 Tomcat 特定的设置吗?
【问题讨论】:
标签: jsp tomcat whitespace
如何从 jsp 页面的输出中去除多余的空格?有没有可以在我的 web.xml 上翻转的开关?有 Tomcat 特定的设置吗?
【问题讨论】:
标签: jsp tomcat whitespace
有一个 trimWhiteSpaces 指令可以完成这个,
在您的 JSP 中:
<%@ page trimDirectiveWhitespaces="true" %>
或者在 jsp-config 部分中您的 web.xml(请注意,这从 servlet 规范 2.5 开始。):
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
</jsp-property-group>
</jsp-config>
不幸的是,如果您有所需的空间,它可能还需要剥离它,因此您可能在某些位置需要一个不间断的空间。
【讨论】:
web.xml: 如果您的 servletcontainer 不支持 JSP 2.1 trimDirectiveWhitespaces 属性,那么您需要查阅其 JspServlet 文档以获取任何初始化参数。例如Tomcat,您也可以通过将trimSpaces init-param 设置为true 来配置它,以便在Tomcat 的JspServlet 中设置JspServlet:
<init-param>
<param-name>trimSpaces</param-name>
<param-value>true</param-value>
</init-param>
一个完全不同的选择是JTidyFilter。它不仅修剪空白,而且还以正确的缩进格式化 HTML。
【讨论】:
不是你想要的,但对我有帮助的是在我的 jsp 标记周围巧妙地放置 HTML 注释标记,并将空格放在 servlet 标记内 ():
${"<!--"}
<c:if test="${first}">
<c:set var="extraClass" value="${extraClass} firstRadio"/>
</c:if>
<c:set var="first" value="${false}"/>
${"-->"}<%
%><input type="radio" id="input1" name="dayChooser" value="Tuesday"/><%
%><label for="input1" class="${extraClass}">Tuesday</label>
【讨论】:
如果你使用标签,你也可以在那里应用:
<%@ tag description="My Tag" trimDirectiveWhitespaces="true" %>
在你的 jsp 上:
<%@ page trimDirectiveWhitespaces="true" %>
【讨论】:
trimDirectiveWhitespaces 仅受支持 JSP 2.1 及更高版本的 servlet 容器支持,或者在这种情况下或 Tomcat、Tomcat 6(以及某些版本,例如 Tomcat 6.0.10 没有正确实现它 - 不了解其他版本) )。 这里有关于 trimDirectiveWhitespaces 的更多信息:
http://www.oracle.com/technetwork/articles/javaee/jsp-21-136414.html
这里
【讨论】:
您可以更进一步,还可以在构建时删除 html 标记之间的换行符(回车)。
例如改变:
<p>Hello</p>
<p>How are you?</p>
进入:
<p>Hello</p><p>How are you?</p>
这样做,使用maven-replacer-plugin 并在pom.xml 中进行设置:
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<id>stripNewlines</id>
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
<configuration>
<basedir>${project.build.directory}</basedir>
<filesToInclude>projectname/WEB-INF/jsp/**/*.jsp</filesToInclude>
<token>>\s*<</token>
<value>><</value>
<regexFlags>
<regexFlag>MULTILINE</regexFlag>
</regexFlags>
</configuration>
</execution>
</executions>
</plugin>
这只会修改 build-directory 中的 JSP,不会触及源代码中的 JSP。
您可能需要调整 JSP 所在的路径 (<filesToInclude>)。
【讨论】:
请使用修剪功能,示例
fn:trim(string1)
【讨论】:
使用
添加/编辑您的 tomcatcatalina.properties 文件
org.apache.jasper.compiler.Parser.STRICT_QUOTE_ESCAPING=false
另请参阅:https://confluence.sakaiproject.org/display/BOOT/Install+Tomcat+7
【讨论】:
有点偏离实际问题,如果您想摆脱在输出之前所做的任何事情导致的空行,您可以使用
out.clearBuffer();
【讨论】: