---
# System prepended metadata

title: JSP 最後還是會被Tomcat9轉譯為 Servlet 原始碼
tags: [Servlet&JSP]

---

###### tags: `Servlet&JSP`

# JSP 最後還是會被Tomcat9轉譯為 Servlet 原始碼
## 希望是觀念?
基本上 Servlet 作的到的功能，使用 JSP 也都作的到。

JSP 最後還是會被容器(web容器 Tomcat9)轉譯為 Servlet 原始碼、自動編譯為 .class 檔案、載入 .class 檔案然後生成 Servlet 物件。

JSP 網頁範例：
```
<!DOCTYPE html>
<html>
    <head>
        <title>Hello! World!</title>
    </head>
    <body>
        <h1>Hello! World!</h1>
    </body>
</html>
```
JSP 網頁最後還是成爲 Servlet，在第一次請求 JSP 時，容器會進行轉譯、編譯與載入的動作（所以第一次請求JSP頁面回應較慢）

由Tomcat9容器轉譯後的 Servlet 類別如下:
```
package org.apache.jsp;

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

public final class helloworld_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
                 org.apache.jasper.runtime.JspSourceImports {

  ...略

  public void _jspInit() {
    // 略...
  }

  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 java.lang.String _jspx_method = request.getMethod();
    if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
      response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
      return;
    }

    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");
      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("<!DOCTYPE html>\r\n");
      out.write("<html>\r\n");
      out.write("    <head>\r\n");
      out.write("        <title>Hello! World!</title>\r\n");
      out.write("    </head>\r\n");
      out.write("    <body>\r\n");
      out.write("        <h1>Hello! World!</h1>\r\n");
      out.write("    </body>\r\n");
      out.write("</html>");
    } catch (java.lang.Throwable t) {

      ...略

    } finally {

      ...略

    }
  }
}
```

現在聚焦於 _jspInit()、 _jspDestroy() 與 _jspService() 這三個方法。