當運行起來後,咱們能夠看看如此短小精悍的神器的原理是什麼?確定會有人有疑惑。下面咱們來初步學習一下。java
首先看web.xml , 能夠看到他只有一個filter(過濾器)。 能夠確定他的核心是filter(過濾器)構成的。web
/** * JFinal framework filter */ public class JFinalFilter implements Filter { private Handler handler; private String encoding; private JFinalConfig jfinalConfig; private Constants constants; private static final JFinal jfinal = JFinal.me(); private static Log log; private int contextPathLength; //方法在 Filter 生命週期中僅執行一次,web 容器在調用 init 方法時 public void init(FilterConfig filterConfig) throws ServletException { //從web.xml裏讀取configClass參數,並初始化jfinalConfig這個類 createJFinalConfig(filterConfig.getInitParameter("configClass")); //初始化一些參數配置 if (jfinal.init(jfinalConfig, filterConfig.getServletContext()) == false) { throw new RuntimeException("JFinal init error!"); } handler = jfinal.getHandler(); constants = Config.getConstants(); encoding = constants.getEncoding(); jfinalConfig.afterJFinalStart(); String contextPath = filterConfig.getServletContext().getContextPath(); contextPathLength = (contextPath == null || "/".equals(contextPath) ? 0 : contextPath.length()); } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)res; request.setCharacterEncoding(encoding); String target = request.getRequestURI(); if (contextPathLength != 0) { target = target.substring(contextPathLength); } boolean[] isHandled = {false}; try { handler.handle(target, request, response, isHandled); } catch (Exception e) { if (log.isErrorEnabled()) { String qs = request.getQueryString(); log.error(qs == null ? target : target + "?" + qs, e); } } if (isHandled[0] == false) { chain.doFilter(request, response); } } public void destroy() { jfinalConfig.beforeJFinalStop(); jfinal.stopPlugins(); } private void createJFinalConfig(String configClass) { if (configClass == null) { throw new RuntimeException("Please set configClass parameter of JFinalFilter in web.xml"); } Object temp = null; try { temp = Class.forName(configClass).newInstance(); } catch (Exception e) { throw new RuntimeException("Can not create instance of class: " + configClass, e); } if (temp instanceof JFinalConfig) { jfinalConfig = (JFinalConfig)temp; } else { throw new RuntimeException("Can not create instance of class: " + configClass + ". Please check the config in web.xml"); } } static void initLog() { log = Log.getLog(JFinalFilter.class); } }
概念解讀學習
Filter : http://www.javashuo.com/article/p-kjjxrnqw-hv.html.net