1. 程式人生 > >tomcat編譯超過64k大小的jsp文件報錯原因

tomcat編譯超過64k大小的jsp文件報錯原因

spfa extend Owner rap start jasper exc true res

今天遇到一個問題,首先是在tomcat中間件上跑的web項目,一個jsp文件,因為代碼行數實在是太多了,更新了幾個版本之後編譯報錯了,頁面打開都是報500的錯誤,500的報錯,知道http協議返回碼的都知道,這是服務端的報錯。

jsp編譯過程是先編譯為servlet,然後再通過類加載器編譯為.class文件,再執行為Servlet實例。這就是jsp的編譯過程。所以jsp報500錯誤也可以理解,屬於服務端的報錯沒什麽好懷疑的。

服務端報錯,肯定就是去console拿日誌了。從CONSOLE拿到日誌關鍵信息:

The code of method _jspService(HttpServletRequest, HttpServletResponse) is exceeding the 65535 bytes limit

這個報錯意思大概是超過字節限制。通過網上資料搜索,很多地方都是給出了一個解決方法,不過大部分都沒說明為什麽。
網上一大堆差不多的博客,都是這樣說的,在tomcat的conf文件夾裏,找到web.xml,然後在JspServlet的servlet配置裏,加上mappedfile參數
修改後的代碼

<servlet>
        <servlet-name>jsp</servlet-name>
        <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
        <init-param>
            <param-name>fork</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>xpoweredBy</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>  
            <param-name>mappedfile</param-name>  
            <param-value>false</param-value>  
        </init-param> 
        <load-on-startup>3</load-on-startup>
    </servlet>

其實也就是加上

<init-param>  
           <param-name>mappedfile</param-name>  
           <param-value>false</param-value>  
 </init-param>

大部分博客並沒有給出原因。不過還是可以解決問題的。不過網上所說的這種方法並不是很好的方法,只能說是暫緩之策。

首先要從jsp的編譯說起,jsp經過tomcat編譯後,文件會保存在哪裏?
下面介紹一下,一般路徑都會在${TOMCAT_HOME}\work\Catalina\localhost\項目名稱\org\apache\jsp文件夾下面。
假如新建了一個index.jsp,經過編譯之後,都會在該路徑下面生成index_jsp.java文件和index_jsp.class文件,index_jsp.java文件是什麽?其實可以理解為tomcat編譯生成的servlet類,index_jsp.class呢?當然就是servlet類編譯之後生成的.class文件了。
隨便找個index_jsp.java文件,拿代碼來看看:

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/7.0.32
 * Generated at: 2016-11-19 03:26:12 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import java.util.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html;charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write(‘\r‘);
      out.write(‘\n‘);
      if (true) {
        _jspx_page_context.forward("/login_toLogin");
        return;
      }
      out.write(‘\r‘);
      out.write(‘\n‘);
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try { out.clearBuffer(); } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}

從代碼可以看出,類繼承於HttpJspBase類實現JspSourceDependent接口,先看一下HttpJspBase類,這個類從哪來的呢?HttpJspBase是tomcat庫提供的,所以拿tomcat庫的源碼來看看,在${TOMCAT_HOME}/lib裏找到價包jasper.jar,反編譯代碼,找到HttpJspBase類

package org.apache.jasper.runtime;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.HttpJspPage;
import org.apache.jasper.compiler.Localizer;

public abstract class HttpJspBase extends HttpServlet
  implements HttpJspPage
{
  private static final long serialVersionUID = 1L;

  public final void init(ServletConfig config)
    throws ServletException
  {
    super.init(config);
    jspInit();
    _jspInit();
  }

  public String getServletInfo()
  {
    return Localizer.getMessage("jsp.engine.info");
  }

  public final void destroy()
  {
    jspDestroy();
    _jspDestroy();
  }

  public final void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    _jspService(request, response);
  }

  public void jspInit()
  {
  }

  public void _jspInit()
  {
  }

  public void jspDestroy()
  {
  }

  protected void _jspDestroy()
  {
  }

  public abstract void _jspService(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
    throws ServletException, IOException;
}

代碼並不是說多復雜,HttpJspBase類繼承HttpServlet類,實現HttpJspPage接口,也就是說HttpJspBase重寫了HttpServlet的service(),init()等等方法,HttpServlet,我們就很熟悉了。HttpJspPage又是什麽?看它的包名,馬上知道它是jdk提供的接口,馬上找到它的代碼:

/*
 * The contents of this file are subject to the terms
 * of the Common Development and Distribution License
 * (the "License").  You may not use this file except
 * in compliance with the License.
 *
 * You can obtain a copy of the license at
 * glassfish/bootstrap/legal/CDDLv1.0.txt or
 * https://glassfish.dev.java.net/public/CDDLv1.0.html.
 * See the License for the specific language governing
 * permissions and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL
 * HEADER in each file and include the License file at
 * glassfish/bootstrap/legal/CDDLv1.0.txt.  If applicable,
 * add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your
 * own identifying information: Portions Copyright [yyyy]
 * [name of copyright owner]
 *
 * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
 *
 * Portions Copyright Apache Software Foundation.
 */
 
package javax.servlet.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * The HttpJspPage interface describes the interaction that a JSP Page
 * Implementation Class must satisfy when using the HTTP protocol.
 *
 * <p>
 * The behaviour is identical to that of the JspPage, except for the signature
 * of the _jspService method, which is now expressible in the Java type
 * system and included explicitly in the interface.
 * 
 * @see JspPage
 */

public interface HttpJspPage extends JspPage {

    /** The _jspService()method corresponds to the body of the JSP page. This
     * method is defined automatically by the JSP container and should never
     * be defined by the JSP page author.
     * <p>
     * If a superclass is specified using the extends attribute, that
     * superclass may choose to perform some actions in its service() method
     * before or after calling the _jspService() method.  See using the extends
     * attribute in the JSP_Engine chapter of the JSP specification.
     *
     * @param request Provides client request information to the JSP.
     * @param response Assists the JSP in sending a response to the client.
     * @throws ServletException Thrown if an error occurred during the 
     *     processing of the JSP and that the container should take 
     *     appropriate action to clean up the request.
     * @throws IOException Thrown if an error occurred while writing the
     *     response for this page.
     */
    public void _jspService(HttpServletRequest request,
                            HttpServletResponse response)
       throws ServletException, IOException;
}

**很關鍵的方法名:_jspService,不就是剛才CONSOLE報錯提示的方法名?
也就是說jdk提供接口,然後tomcat對接口進行實現,我們知道Java內存模型(JMM)規定了一個方法的大小只能是64k,所以,從剛才的報錯,我們簡單從源碼分析了一下,報錯的原因其實就是jsp反編譯為Servlet之後,代碼要經過_jspService這個方法,這個方法超過了64k,導致報錯。**

查看一下tomcat7官方給出的文檔:http://tomcat.apache.org/tomcat-7.0-doc/jasper-howto.html#Configuration
找到mappedfile屬性的意思

mappedfile - 我們是否應該為每個輸入行生成一個print語句的靜態內容,以便於調試? true或者false,默認true。

現在分析一下具體原因。代碼報錯的原因就是因為jsp編譯為Servlet之後,經過_jspService這個方法,方法超過64k導致報錯。然後通過設置mappedfile參數的原因是盡量減少print代碼,暫時使代碼不超過,也就是說只是一種暫緩的方法。網上資料說通過

tomcat編譯超過64k大小的jsp文件報錯原因