概述
在Servlet中编写HTML太麻烦了,应该使用JSP。JSP中可以直接编写HTML,使用指示、声明、脚本(scriptlet)等元素来堆砌各种功能,但JSP最后还是会被容器转译为Servlet源代码、自动编译为.class文件、载入.class文件,然后生成Servlet对象。
在第一次请求JSP时,容器会进行转译、编译与加载的操作,所以第一次请求JSP页面会慢很多。
源码分析
若使用Tomcat 7或Glassfish v3作为Web容器,最后由容器转译后的Servlet类是继承自HttpJspBase类,而HttpJspBase又继承了HttpServlet。
下面是HttpJspBase类的源码,这个类的源码可以在Tomcat的lib目录下的 jasper.jar\org\apache\jasper\runtime 这个文件夹找到。
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; protected HttpJspBase() { } public final void init(ServletConfig config) throws ServletException { super.init(config); this.jspInit(); this._jspInit(); } public String getServletInfo() { return Localizer.getMessage("jsp.engine.info"); } public final void destroy() { this.jspDestroy(); this._jspDestroy(); } public final void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this._jspService(request, response); } public void jspInit() {} public void _jspInit() {} public void jspDestroy() {} protected void _jspDestroy() {} public abstract void _jspService(HttpServletRequest var1, HttpServletResponse var2) throws ServletException, IOException; }