方便将css、js、pic资源文件打包进jar里
package com.hszdz.jfinal; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.jfinal.handler.Handler; import com.jfinal.kit.LogKit; /** * * @author hszdz(qq:58875000) * */ public class ResHandler extends Handler { private String resBase = "/res/"; public ResHandler(String resBase) { this.resBase = resBase; } public ResHandler() { } @Override public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) { if (!target.startsWith(resBase)) { next.handle(target, request, response, isHandled); return; } InputStream is = getClass().getResourceAsStream(target); if (is == null) { next.handle(target, request, response, isHandled); return; } try { try { // LogKit.info("handler jar resource:" + target); isHandled[0] = true; String contentType = getContentType(target); response.setContentType(contentType); copy(is, response.getOutputStream()); response.setHeader("Cache-Control", "max-age=3600"); } finally { is.close(); } } catch (Exception e) { LogKit.error(target + "发生错误:" + e.getMessage()); } } protected String getContentType(String name) { if (name.endsWith(".js")) { return "text/javascript"; } else if (name.endsWith(".css")) { return "text/css"; } else if (name.endsWith(".html")) { return "text/html"; } else if (name.endsWith(".txt")) { return "text/plain"; } else if (name.endsWith(".gif")) { return "image/gif"; } else if (name.endsWith(".jpg") || name.endsWith(".jpeg")) { return "image/jpeg"; } else if (name.endsWith(".png")) { return "image/png"; } else { return null; } } protected void copy(InputStream input, OutputStream output) throws IOException { final byte[] buffer = new byte[4096]; int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } output.flush(); } }
但如果是servlet3.0的话,容器本身就支持访问resource/META-INF/resource下的静态资源