JSP发布清除空格换行

来源:互联网 发布:数据库系统概论 课件 编辑:程序博客网 时间:2024/05/22 14:19

JSP生成的html里面会留下许多空白行(以及space, tab, etc.),那是动态语句留下的痕迹。当初留下这些空白行自然有他的理由 - 方便调试,这样行号才能对的上。但是对于处于production环境中的页面,这么多空白行有时候会是个灾难,常见原因有二: a. 大大增加了页面体积; b. 不利于SEO.

1、tomcat 5.x以后新加入了一个参数来解决这个问题,那就是
<init-param>
<param-name>trimSpaces</param-name>
<param-value>true</param-value>
</init-param>

 

2、用eclipse里的ant工具清除空格、换行

ant的xml代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project name="replace" basedir="./../../" default="">
    <!--<property name="ant.regexp.regexpimpl" value="org.apache.tools.ant.util.regexp.JakartaOroRegexp"/>-->
    <property name="targetDir" value="D:/workspace-mall-deploy/mall" />
    <!-- strip blank lines before webpage -->
    <target name="replace-jsp-jspf-tag">

        <replaceregexp byline="true" encoding="utf-8"><!-- 清除行首尾空格-->
            <regexp pattern="^/s*|/s*$"/>
            <substitution expression=""/>
            <fileset dir="${targetDir}/web/" includes="**/*.jsp,**/*.jspf,**/*.tag"/>
        </replaceregexp>

        <replaceregexp match="/r/n" replace=""  flags="g" byline="false"><!-- 清除换行/tab-->
            <fileset dir="${targetDir}/web/" includes="**/*.jsp,**/*.jspf,**/*.tag" />
        </replaceregexp>
    </target>
    <target name="replace-css-js">
        <replaceregexp match="/r/n" replace=""  flags="g" byline="false">
            <fileset dir="${targetDir}/web/" includes="**/*.js,**/*.css" />
        </replaceregexp>
    </target>
</project>

     这个方式注意把jsp页面里的//和js代码的//注释清除掉后再执行。为此,程序员必须养成良好规范的编程习惯,如注释用<!-- html -->,/* js,java */ , <%-- jsp --%>;另外代码块要严格用{} 分块, 如很多程序员习惯 else name="sdfdf",else直接换行写单行代码,在清除首尾空格及换行时,都会出现异常。

原创粉丝点击