Friday, 29 November 2013

Precompile your JSP's

The Jsp Pages are normally not pre-compiled for deployment . But We can pre-compile the JSP pages if neccessary specific to the application server(tomcat/weblogic server) . The file will just be compiled and the request will not be served . Hence it can be considered to be pre-compiled. The jsp_precompile parameter may have no value, or may have values true or false. It should not have any other values like ?jsp_precompile=yes – this will result in HTTP error 500.
So the example for query strings to pre compile jsp files are
?jsp_precompile
?jsp_precompile=true
?jsp_precompile=false
?foobar=foobaz&jsp_precompile=true
?foobar=foobaz&jsp_precompile=false

There are no special features available for this in the JSP specification. But the application servers (JSP containers) provide methods to do this on their own way. At the end of this tutorial we will see how to pre compile JSP files for Apache Tomcat 6. But if you want to pre compile in server independent manner you have to use jsp_precompile request parameter and no other option available. To do it for the whole application, you can custom write a servlet or jsp file which will raise a request for all the JSPs available with jsp_precompile added as parameter.


<%@ page import="javax.servlet.*,javax.servlet.http.*,javax.servlet.jsp.* "%>
<%@ page import="java.util.Set,java.util.Iterator,java.io.IOException"%>
<%!
  private void preCompileJsp(PageContext pageContext, JspWriter out,
   HttpServletRequest request, HttpServletResponse response, String uripath)
   throws IOException, ServletException {

     // getting jsp files list for pre compilation
     Set jspFilesSet = pageContext.getServletContext().getResourcePaths(uripath);
     for (Iterator jspFilesSetItr = jspFilesSet.iterator(); jspFilesSetItr.hasNext();) {
         String uri = (String) jspFilesSetItr.next();
         if (uri.endsWith(".jsp")) {
             RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
             if (rd == null) throw new Error(uri +" - not found");
             rd.include(request, response);
         }
         else if (uri.endsWith("/")) {
             preCompileJsp(pageContext, out, request, response, uri);
         }
     }
   }
%>
<html><head><title>Pre Compile JSP Files</title></head>
<body>
<%
  HttpServletRequest req = new HttpServletRequestWrapper(request) {
      public String getQueryString() {
          // setting the pre compile parameter
          return "jsp_precompile";
      };
  };
  preCompileJsp(pageContext, out, req, response, "/");
%>
JSP files Pre Compile Completed.

</body></html>

No comments:

Post a Comment