Created
May 12, 2021 14:54
-
-
Save krisfoster/45a8cf3b8a3a9330bb346aa5f68b762e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example.web.graal; | |
import org.apache.tomcat.util.descriptor.web.ServletDef; | |
import org.apache.tomcat.util.descriptor.web.WebXml; | |
import org.apache.tomcat.util.descriptor.web.WebXmlParser; | |
import org.springframework.beans.factory.annotation.Value; | |
import org.springframework.boot.web.servlet.ServletContextInitializer; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.core.io.Resource; | |
import org.xml.sax.InputSource; | |
import javax.servlet.ServletRegistration; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.util.Map; | |
@Configuration | |
public class PreCompiledJSPConfiguration { | |
// Mapping xml created by the bmuschko.tomcat plugin | |
@Value("classpath:WEB-INF/web.xml") | |
private Resource precompiledJspWebXml; | |
@Bean | |
public ServletContextInitializer registerPreCompiledJsps() { | |
return servletContext -> { | |
// Use Tomcat's web.xml parser (assume complete XML file and validate). | |
WebXmlParser parser = new WebXmlParser(false, true, true); | |
try (InputStream is = precompiledJspWebXml.getInputStream()) { | |
WebXml webXml = new WebXml(); | |
boolean success = parser.parseWebXml(new InputSource(is), webXml, false); | |
if (!success) { | |
System.out.println("Possible problem when parsing " + precompiledJspWebXml); | |
} | |
for (ServletDef def : webXml.getServlets().values()) { | |
System.out.printf("Registering precompiled JSP: {%s} -> {%s}", def.getServletName(), def.getServletClass()); | |
ServletRegistration.Dynamic reg = servletContext.addServlet(def.getServletName(), def.getServletClass()); | |
reg.setLoadOnStartup(99); | |
} | |
for (Map.Entry<String, String> mapping : webXml.getServletMappings().entrySet()) { | |
System.out.printf("Mapping servlet: {%s} -> {%s}", mapping.getValue(), mapping.getKey()); | |
servletContext.getServletRegistration(mapping.getValue()).addMapping(mapping.getKey()); | |
} | |
} catch (IOException e) { | |
throw new RuntimeException("Error registering precompiled JSPs", e); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment