从jsp输出中删除空格

如何从jsp页面的输出中去掉多余的空白? 有我可以翻转我的web.xml的开关? 有一个Tomcat的具体设置?

有一个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> 

不幸的是,如果你有一个需要的空间,它可能也需要剥离,所以你可能需要在一些地方没有破空间。

如果您的servletcontainer不支持JSP 2.1 trimDirectiveWhitespaces属性,则需要查阅其JspServlet文档以获取任何初始化参数。 例如在Tomcat中 ,您可以通过在Tomcat的/conf/web.xml中为JspServlet中的/conf/web.xml init-param设置true来进行/conf/web.xml

 <init-param> <param-name>trimSpaces</param-name> <param-value>true</param-value> </init-param> 

JTidyFilter完全不同。 它不仅修剪空白,而且还将HTML 格式化为正确的缩进。

trimDirectiveWhitespaces只支持JSP 2.1以及之后的Tomcat容器,或Tomcat Tomcat 6(以及Tomcat 6.0.10的某些版本没有正确实现 – 不知道其他的版本)。 这里有更多有关trimDirectiveWhitespaces的信息:

http://java.sun.com/developer/technicalArticles/J2EE/jsp_21/

和这里

http://raibledesigns.com/rd/entry/trim_spaces_in_your_jsp1

不是直接询问你的内容,但是帮助我将HTML注释标签放在我的jsp标签中,同时在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" %> 

添加/编辑您的tomcat catalina.properties文件

 org.apache.jasper.compiler.Parser.STRICT_QUOTE_ESCAPING=false 

另见: https : //confluence.sakaiproject.org/display/BOOT/Install+Tomcat+7

你可以更进一步,也可以在构build时间去掉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>&gt;\s*&lt;</token> <value>&gt;&lt;</value> <regexFlags> <regexFlag>MULTILINE</regexFlag> </regexFlags> </configuration> </execution> </executions> </plugin> 

这只会修改构build目录中的JSP,而不会触及源代码中的JSP。

您可能需要调整您的JSP所在的path( <filesToInclude> )。