How to prevent caching of static files in embedded

2019-02-14 16:03发布

I want to prevent my CSSs from being cached on the browser side. How can I do it in embedded Jetty instance?

If I were using xml configuration file, I would add lines like:

<init-param>
  <param-name>cacheControl</param-name>
  <param-value>max-age=0,public</param-value>
</init-param>

How I can turn that into the code?

Right now I start Jetty this way:

BasicConfigurator.configure();

Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
// 1 hour
connector.setMaxIdleTime( 1000 * 60 * 60 );
connector.setSoLingerTime( -1 );
connector.setPort( 8081 );
server.setConnectors( new Connector[] { connector } );

WebAppContext bb = new WebAppContext();
bb.setServer( server );
bb.setContextPath( "/" );
bb.setWar( "src/webapp" );

server.addHandler( bb );

I think I should search setControlCache somewhere in the WebAppContext area of responsibility.

Any advices on this?

4条回答
劫难
2楼-- · 2019-02-14 16:26

I normally use a ServletHolder, like this:

WebAppContext context = new WebAppContext();
ServletHolder servletHolder = new ServletHolder(MyServlet.class);
servletHolder.setInitParameter("cacheControl","max-age=0,public"); 
context.addServlet(servletHolder, "myservletpath");

While this does not exactly match your code you should be able to figure it out from there ?

查看更多
【Aperson】
4楼-- · 2019-02-14 16:31

And here's just a working code with no need to figure out, guess and try. It's provided with respect to code in question and jetty 6. For jetty 7 and higher need to change Context to ServletContextHandler.

BasicConfigurator.configure();

Server server = new Server();
SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
// 1 hour
connector.setMaxIdleTime( 1000 * 60 * 60 );
connector.setSoLingerTime( -1 );
connector.setPort( 8081 );
server.setConnectors( new Connector[] { connector } );

//--- The difference with code in question starts here

DefaultServlet defaultServlet = new DefaultServlet();
ServletHolder holder = new ServletHolder(defaultServlet);
holder.setInitParameter("useFileMappedBuffer", "false");
holder.setInitParameter("cacheControl", "max-age=0, public");

Context bb = new Context();
bb.setResourceBase("src/webapp");
bb.addServlet(holder, "/");

//--- Done. Caching is off!

server.addHandler( bb );
// Run server as usual with server.run();

My sample also sets useFileMappedBuffer to false which is needed for not blocking files on a disk if you are developing on Windows by any reason.

查看更多
乱世女痞
5楼-- · 2019-02-14 16:42

I use resourceHandler for static contents. Here's a code working fine on Jetty 9.

    ResourceHandler rh = new ResourceHandler();
    rh.setResourceBase([your_resource_base_dir]);
    rh.setCacheControl("no-store,no-cache,must-revalidate");
查看更多
登录 后发表回答