- 当你在客户端用view source看JSP生成的代码时,会发现有很多空行,他们是由< %...% >后的回车换行而生成的,也就是说每一行由< %...% >包含的JSP代码到客户端都变成一个空行,虽然不影响浏览,但还是希望能把他们删掉。这里将为大家介绍如何删除JSP编译后的空行。
Tomcat删除JSP编译后的空行办法如下:
1. 支持JSP 2.1+ ,在每个要去空行的页面里包含下面代码:
- <%@ page trimDirectiveWhitespaces="true" %>
在 Tomcat 6.0.14下测试JSP编译成功
2. 支持servlet 2.5+, 即 web.xml的 XSD版本为2.5,在web.xml中加入如下代码
- <jsp-config>
- <jsp-property-group>
- <url-pattern>*.jsp</url-pattern>
- <trim-directive-whitespaces>true</trim-directive-whitespaces>
- </jsp-property-group>
- </jsp-config>
在tomcat 6.0.14下测试JSP编译成功
3. Tomcat 5.5.x+,在Tomcat安装目录/conf/web.xml中找到名叫"jsp"的servlet,添加下面一段代码:
- <init-param>
- <param-name>trimSpaces</param-name>
- <param-value>true</param-value>
- </init-param>
本人没测过,不过tomcat中web.xml文件的帮助这么说的
trimSpaces Should white spaces in template text between actions or directives be trimmed? [false]
在实际操作中我加入了5.5的配置到页面中并反复启动了几次tomcat但是还是没有成功,后来才想到JSP已经编译成servlet了所以没有能改变,进入到tomcat中的work目录把已经进行JSP编译的class全部删除,哇哈哈,整个世界清净了,成功删除空行
resin删除JSP编译后的空行办法如下:
I'm getting a lot of whitespace in my JSP that I don't intend to be there. Why is it appearing and how can I get rid of it?
The extra whitespace is coming from newlines, often at the end of declaration lines at the beginning of the JSP. For example, the following jsp:
<%@ page import='java.util.*' %> <%@ page import='java.io.*' %> Hello world
Has newlines in these locations:
<%@ page import='java.util.*' %>NL <%@ page import='java.io.*' %>NL Hello worldNL
The result contains the newlines, which may be surprising:
Hello world
One solution is to let the JSP tag extend across the newline:
<%@ page import='java.util.*' %><%@ page import='java.io.*' %>Hello world
Another solution is to use JSP comments to remove the newlines:
<%@ page import='java.util.*' %><%-- --%><%@ page import='java.io.*' %><%-- --%>Hello world
Another solution is to use the XML syntax of JSP. Parsing of XML causes removal of extra whitespace.
<jsp:root> <jsp:directive.page import="java.util.*"/> <jsp:directive.page import="java.io.*"/> <jsp:text>Hello world</jsp:text> </jsp:root>
Resin also supports the use of the '/' character to eat whitespace (this is a Resin specific feature):
<%@ page import='java.util.*' %>/ <%@ page import='java.io.*' %>/ Hello world