一些JSP容器(例如规范中的第8.4.2节点提到的)支持对JSP页面进行预编译的能力
为了预编译一个JSP页面, 我们访问这个页面需要使用?jsp_precompile这样的模式
例如:

[url]http://hostname.com/mywebapp/mypage.jsp?jsp_precompile[/url]

这个JSP页面不会被执行,如果容器支持预编译,这个jsp页面将会按照要求被编译.

下面是一个JSP页面,这个页面将会扫描当前目录(包括子目录),并且预编译这些目录下所有的JSP文件.


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.jsp.*"%>
<%@ page import="java.util.Set,java.util.Iterator,java.io.IOException"%>

<%! private void compileAllJsps
     (PageContext pageContext, JspWriter out,
      HttpServletRequest request,HttpServletResponse response,
      String uripath)
         throws IOException, ServletException {

     Set set = pageContext.getServletContext().getResourcePaths(uripath);
     for (Iterator iter = set.iterator(); iter.hasNext();) {
         String uri = (String) iter.next();
         if (uri.endsWith(".jsp")) {
             out.write("<li>"+ uri +"</li>");
             out.flush();
             RequestDispatcher rd =
                getServletContext().getRequestDispatcher(uri);
             if (rd == null) {
                 throw new Error(uri +" - not found");
                 }
             rd.include(request, response);
         }
         else if (uri.endsWith("/")) {
             compileAllJsps(pageContext, out, request, response, uri);
         }
     }
   }
%>

<html><head><title>Precompiling *.JSPs</title></head>
<body><h4>Precompiling *.JSPs:</h4>
<ul>
<%
  HttpServletRequest req = new HttpServletRequestWrapper(request) {
      public String getQueryString() {
          // can be "jsp_precompile=true"
          return "jsp_precompile";
          };
  };
  compileAllJsps(pageContext, out, req, response, "/");
%>
</ul>
<h4>Done.</h4>
</body> </html>

主意:很多中间件服务器提供预编译JSP页面的工具(如EAServer,BEAWLS等)去检查一个JSPC命令文件.

转载请注明本文来自程式先锋网站 www.javabiz.cn