I can't seem to get my jetty to work with caching. I have a jetty server that will display html only. I have JavaScripts in there and a lot of images which I don't want to load every time. For example my application needs to switch in 10 seconds between 3 pages. Loading jQuery three times is time consuming and loading the logo picture and all that takes even longer. That's why I want to enable Caching.
This is what I got:
server = new Server(); //new Jetty Server
//setting up a ssl connection
try
{
SslContextFactory cf = new SslContextFactory();
cf.setKeyStorePath(keystore);
cf.setKeyStorePassword("password");
HttpConfiguration config = new HttpConfiguration();
config.addCustomizer(new SecureRequestCustomizer());
config.setSecureScheme("https");
config.setSecurePort(8443);
HttpConfiguration sslConfiguration = new HttpConfiguration(config);
sslConfiguration.addCustomizer(new SecureRequestCustomizer());
httpConnector = new ServerConnector(server);
httpConnector.addConnectionFactory(new HttpConnectionFactory(config));
httpConnector.setPort(suggestHttpPort());
httpConnector.setName("unsecured");
sslConnector = new ServerConnector(server,
new SslConnectionFactory(cf, HttpVersion.HTTP_1_1.toString()),
new HttpConnectionFactory(sslConfiguration));
sslConnector.setPort(suggestHttpSSLPort());
sslConnector.setName("secured");
server.setConnectors(new Connector[] { httpConnector, sslConnector });
}
catch (Exception e)
{
log.error("setting up Jetty failed", e);
}
// This is where i want to enable caching, at least that is what i have figuged out so far but its not working
DefaultServlet defaultServlet = new DefaultServlet();
ServletHolder holder = new ServletHolder(defaultServlet);
holder.setInitParameter("cacheControl", "max-age=120, public");
ServletContextHandler bb = new ServletContextHandler();
bb.addServlet(holder, "/");
server.setHandler(bb);
server.start();
What am I doing wrong? I want to enable caching for everything...
Don't use ServletHolder
directly like that against a started Servlet, let the ServletHolder
create and init the class reference instead.
You'll want a ServletContextHandler
and a defined Base Resource that the DefaultServlet
can utilize as well (this should be a URI pointing to the root of your static file content)
Example:
ServletContextHandler context = new ServletContextHandler();
context.setContextPath("/");
context.setBaseResource(Resource.newResource(webRootUri));
ServletHolder holderPwd = new ServletHolder("default", DefaultServlet.class);
holderPwd.setInitParameter("dirAllowed", "true");
holderPwd.setInitParameter("cacheControl", "max-age=3600,public");
context.addServlet(holderPwd,"/");
server.setHandler(context);