Skip to content

Instantly share code, notes, and snippets.

@barrypitman
Created January 25, 2013 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barrypitman/4637213 to your computer and use it in GitHub Desktop.
Save barrypitman/4637213 to your computer and use it in GitHub Desktop.
/**
* http://pukkaone.github.com/2010/12/22/jsp-precompile-application-start.html
* <p/>
* Allows for all JSPs to be compiled with a single request to
* http://localhost:8080/actrack/index.html?jsp_precompile_all
* <p/>
* Use a locking flag to make sure that this operation can only be run once (to prevent possible DoS attacks)
*
* @author barry
* @since 2013/01/25 11:46 AM
*/
public class PrecompileAllJspsFilter implements Filter {
private static final String PRECOMPILE_ALL_PARAMETER = "jsp_precompile_all";
private ServletContextResourcePatternResolver resolver;
private final AtomicBoolean hasRun = new AtomicBoolean(false);
private static final Logger LOG = LoggerFactory.getLogger(PrecompileAllJspsFilter.class);
public void init(FilterConfig config) throws ServletException {
resolver = new ServletContextResourcePatternResolver(config.getServletContext());
}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (request.getParameter(PRECOMPILE_ALL_PARAMETER) != null) {
compileAllJsps(request, response);
return;
}
chain.doFilter(req, resp);
}
private void compileAllJsps(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
if (hasRun.getAndSet(true)) {
LOG.warn("Skipping JSP compilation - already run once!");
response.setStatus(200);
return;
}
Resource[] jsps = resolver.getResources("/**/*.jsp");
compile(request, response, jsps);
}
private void compile(HttpServletRequest request, HttpServletResponse response, Resource[] jsps) throws ServletException, IOException {
LOG.info("Precompiling " + jsps.length + " JSPs");
boolean anyErrors = false;
for (Resource jsp : jsps) {
try {
String path = ((ServletContextResource) jsp).getPathWithinContext();
LOG.info("Compiling " + path);
request.getRequestDispatcher(path).include(new RequestWrapper(request), response);
} catch (Exception e) {
anyErrors = true;
LOG.error(e.getMessage());
}
}
response.setStatus(anyErrors ? 500 : 200);
}
public void destroy() {
}
private static class RequestWrapper extends HttpServletRequestWrapper {
public RequestWrapper(HttpServletRequest request) {super(request);}
@Override
public String getQueryString() {
return "jsp_precompile";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment