一切始於 web.xml 中配置的 Filter:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xmlns:web="https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <filter> <filter-name>jfinal</filter-name> <filter-class>com.jfinal.core.JFinalFilter</filter-class> <init-param> <param-name>configClass</param-name> <param-value>com.fw.config.MppConfig</param-value> </init-param> </filter> <filter-mapping> <filter-name>jfinal</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
容器初始化時會載入 JFinalFilter 並呼叫其 init 方法:
public final 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;
public void init(FilterConfig filterConfig) throws ServletException {
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());
}
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");
}
// ...
}
init 的參數正是 web.xml 中 JFinalFilter 的初始化參數 com.fw.config.MppConfig,它繼承自 JFinalConfig,createJFinalConfig 透過反射機制據此建立 JFinalConfig 實例。
boolean init(JFinalConfig jfinalConfig, ServletContext servletContext) {
this.servletContext = servletContext;
this.contextPath = servletContext.getContextPath();
initPathUtil();
Config.configJFinal(jfinalConfig);
constants = Config.getConstants();
initActionMapping();
initHandler();
initRender();
initOreillyCos();
initTokenManager();
return true;
}
第一步:initPathUtil,初始化 PathKit 的 webRootPath,也就是專案根路徑。
private void initPathUtil() {
String path = servletContext.getRealPath("/");
PathKit.setWebRootPath(path);
}
第二步:Config.configJFinal,載入 JFinalConfig 實例並依序完成各項配置。
static void configJFinal(JFinalConfig jfinalConfig) {
jfinalConfig.configConstant(constants);
initLogFactory();
jfinalConfig.configRoute(routes);
jfinalConfig.configPlugin(plugins);
startPlugins(); // very important!!!
jfinalConfig.configInterceptor(interceptors);
jfinalConfig.configHandler(handlers);
}
順序是:配置常量、初始化 Log 工具類、配置路由、配置外掛、啟動外掛、配置攔截器、配置 handler。以下是專案中的實作:
public class MppConfig extends JFinalConfig {
// 配置常量
public void configConstant(Constants me) {
PropKit.use("jdbc.properties");
me.setDevMode(PropKit.getBoolean("devMode", false));
}
// 配置路由
public void configRoute(Routes me) {
me.add(new RoutesMapping());
}
public static C3p0Plugin createC3p0Plugin() {
return new C3p0Plugin(PropKit.get("jdbcUrl"), PropKit.get("user"), PropKit.get("password").trim());
}
// 配置外掛
public void configPlugin(Plugins me) {
// 配置 C3p0 資料庫連接池外掛
C3p0Plugin c3p0Plugin = createC3p0Plugin();
me.add(c3p0Plugin);
// 配置 ActiveRecord 外掛
ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
me.add(arp);
// 配置屬性名(欄位名)大小寫不敏感的容器工廠,適用 Oracle
arp.setContainerFactory(new CaseInsensitiveContainerFactory());
// 緩存外掛
me.add(new EhCachePlugin());
// 所有配置在 MappingKit 中搞定
ModelMapping.mapping(arp);
}
// 配置全域攔截器
public void configInterceptor(Interceptors me) {
me.add(new SessionInViewInterceptor()); // session 攔截器,用於在 View 模板中取出 session 值
}
// 配置處理器,接管所有 web 請求
public void configHandler(Handlers me) {
me.add(new ContextPathHandler("contextPath")); // 設定上下文路徑
}
// 系統啟動完成後回呼,如建立調度線程
public void afterJFinalStart() {}
// 系統關閉前回呼,如寫回緩存
public void beforeJFinalStop() {}
}
第三步:初始化 ActionMapping、Handler、Render、上傳元件與 TokenManager。
private void initActionMapping() {
actionMapping = new ActionMapping(Config.getRoutes(), Config.getInterceptors());
actionMapping.buildActionMapping();
Config.getRoutes().clear();
}
它建立 ActionMapping,把訪問路徑與對應的 Action 兩兩映射,填充成一個 HashMap:
final class ActionMapping {
private static final String SLASH = "/";
private Routes routes;
private final Map<String, Action> mapping = new HashMap<String, Action>();
ActionMapping(Routes routes, Interceptors interceptors) {
this.routes = routes;
}
private Set<String> buildExcludedMethodName() {
Set<String> excludedMethodName = new HashSet<String>();
Method[] methods = Controller.class.getMethods();
for (Method m : methods) {
if (m.getParameterTypes().length == 0)
excludedMethodName.add(m.getName());
}
return excludedMethodName;
}
void buildActionMapping() {
mapping.clear(); // 初始化時先清空
Set<String> excludedMethodName = buildExcludedMethodName(); // Controller 介面的所有無參數方法
InterceptorManager interMan = InterceptorManager.me();
for (Entry<String, Class<? extends Controller>> entry : routes.getEntrySet()) {
Class<? extends Controller> controllerClass = entry.getValue();
Interceptor[] controllerInters = interMan.createControllerInterceptor(controllerClass);
boolean sonOfController = (controllerClass.getSuperclass() == Controller.class); // 此處必為 true
Method[] methods = (sonOfController ? controllerClass.getDeclaredMethods() : controllerClass.getMethods());
for (Method method : methods) {
String methodName = method.getName();
// 繼承自 Controller 的方法或有參數的方法,過濾掉
if (excludedMethodName.contains(methodName) || method.getParameterTypes().length != 0) continue;
// 非 public 方法,過濾掉
if (sonOfController && !Modifier.isPublic(method.getModifiers())) continue;
// 能走到這裡的方法必須:非繼承自 Controller、無參數、且為 public
Interceptor[] actionInters = interMan.buildControllerActionInterceptor(controllerInters, controllerClass, method);
String controllerKey = entry.getKey();
ActionKey ak = method.getAnnotation(ActionKey.class);
String actionKey;
// ActionKey 不為空時使用自訂路徑(該方法標注了 @ActionKey)
if (ak != null) {
actionKey = ak.value().trim();
if ("".equals(actionKey))
throw new IllegalArgumentException(controllerClass.getName() + "." + methodName + "(): The argument of ActionKey can not be blank.");
if (!actionKey.startsWith(SLASH)) actionKey = SLASH + actionKey;
}
// ActionKey 為空且 methodName 為 index:actionKey = controllerKey
else if (methodName.equals("index")) {
actionKey = controllerKey;
}
// ActionKey 為空且 methodName 不為 index:actionKey = controllerKey + "/" + methodName
else {
actionKey = controllerKey.equals(SLASH) ? SLASH + methodName : controllerKey + SLASH + methodName;
}
Action action = new Action(controllerKey, actionKey, controllerClass, method, methodName, actionInters, routes.getViewPath(controllerKey));
if (mapping.put(actionKey, action) != null)
throw new RuntimeException(buildMsg(actionKey, controllerClass, method));
}
}
// 支援 url = controllerKey + urlParas 且 controllerKey 帶 "/"
Action action = mapping.get("/");
if (action != null) mapping.put("", action);
}
// ...
}
之後 Config.routes 已無用處,因此被清空。
private void initHandler() {
Handler actionHandler = new ActionHandler(actionMapping, constants);
handler = HandlerFactory.getHandler(Config.getHandlers().getHandlerList(), actionHandler);
}
HandlerFactory 會組出一條 Handler 鏈,鏈尾是 ActionHandler,回傳的是鏈首:
public class HandlerFactory {
private HandlerFactory() {}
/** 建立 handler 鏈條,回傳的 result 是鏈頭,鏈尾是 ActionHandler */
@SuppressWarnings("deprecation")
public static Handler getHandler(List<Handler> handlerList, Handler actionHandler) {
Handler result = actionHandler;
for (int i = handlerList.size() - 1; i >= 0; i--) {
Handler temp = handlerList.get(i);
temp.next = result;
temp.nextHandler = result;
result = temp;
}
return result;
}
}
private void initRender() {
RenderFactory.me().init(constants, servletContext);
}
RenderFactory 負責初始化各類視圖渲染器,並依設定的預設視圖型別建立 mainRenderFactory:
public class RenderFactory {
public void init(Constants constants, ServletContext servletContext) {
this.constants = constants;
this.servletContext = servletContext;
// 初始化 Render:編碼與開發模式
Render.init(constants.getEncoding(), constants.getDevMode());
initFreeMarkerRender(servletContext);
initVelocityRender(servletContext);
initJspRender(servletContext);
initFileRender(servletContext);
// 建立 mainRenderFactory
if (mainRenderFactory == null) {
ViewType defaultViewType = constants.getViewType();
if (defaultViewType == ViewType.FREE_MARKER) {
mainRenderFactory = new FreeMarkerRenderFactory();
} else if (defaultViewType == ViewType.JSP) {
mainRenderFactory = new JspRenderFactory();
} else if (defaultViewType == ViewType.VELOCITY) {
mainRenderFactory = new VelocityRenderFactory();
} else {
throw new RuntimeException("View Type can not be null.");
}
}
if (errorRenderFactory == null) errorRenderFactory = new ErrorRenderFactory();
if (xmlRenderFactory == null) xmlRenderFactory = new XmlRenderFactory();
}
private void initFreeMarkerRender(ServletContext servletContext) {
try {
Class.forName("freemarker.template.Template"); // 載入 freemarker 模板
FreeMarkerRender.init(servletContext, Locale.getDefault(), constants.getFreeMarkerTemplateUpdateDelay());
} catch (ClassNotFoundException e) {
LogKit.logNothing(e); // 載入模板失敗,例如未引入 jar 包
}
}
// ...
}
FreeMarkerRender 的靜態初始化設定了模板位置、更新延遲、異常處理器、物件包裝器、編碼、時區與數字/日期格式:
public class FreeMarkerRender extends Render {
private static final String contentType = "text/html; charset=" + getEncoding();
private static final Configuration config = new Configuration();
static void init(ServletContext servletContext, Locale locale, int template_update_delay) {
config.setServletContextForTemplateLoading(servletContext, "/"); // 模板存放位置為專案根路徑
if (getDevMode()) {
config.setTemplateUpdateDelay(0); // 開發模式下即時更新
} else {
config.setTemplateUpdateDelay(template_update_delay);
}
config.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
config.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
config.setDefaultEncoding(getEncoding());
config.setOutputEncoding(getEncoding());
config.setLocale(locale);
config.setLocalizedLookup(false);
config.setNumberFormat("#0.#####"); // 去掉 int 輸出時的逗號,例如 123,456
config.setDateFormat("yyyy-MM-dd");
config.setTimeFormat("HH:mm:ss");
config.setDateTimeFormat("yyyy-MM-dd HH:mm:ss");
}
// ...
}
private void initOreillyCos() {
OreillyCos.init(constants.getBaseUploadPath(), constants.getMaxPostSize(), constants.getEncoding());
}
OreillyCos 先嘗試載入上傳元件類,成功後再完成初始化,並把上傳路徑加工成絕對路徑:
public class OreillyCos {
// 先載入上傳元件
public static void init(String uploadPath, int maxPostSize, String encoding) {
if (StrKit.isBlank(uploadPath))
throw new IllegalArgumentException("uploadPath can not be blank.");
try {
Class.forName("com.oreilly.servlet.MultipartRequest");
doInit(uploadPath, maxPostSize, encoding);
} catch (ClassNotFoundException e) {
LogKit.logNothing(e);
}
}
private static void doInit(String uploadPath, int maxPostSize, String encoding) {
uploadPath = uploadPath.trim();
uploadPath = uploadPath.replaceAll("\\\\", "/");
String baseUploadPath;
// 判斷上傳路徑是否為絕對路徑,不是則加工成絕對路徑
if (PathKit.isAbsolutelyPath(uploadPath)) {
baseUploadPath = uploadPath;
} else {
baseUploadPath = PathKit.getWebRootPath() + File.separator + uploadPath;
}
// 移除結尾的 "/"
if (baseUploadPath.equals("/") == false) {
if (baseUploadPath.endsWith("/")) {
baseUploadPath = baseUploadPath.substring(0, baseUploadPath.length() - 1);
}
}
MultipartRequest.init(baseUploadPath, maxPostSize, encoding);
}
// ...
}
public class MultipartRequest extends HttpServletRequestWrapper {
private static String baseUploadPath;
private static int maxPostSize;
private static String encoding;
static void init(String baseUploadPath, int maxPostSize, String encoding) {
MultipartRequest.baseUploadPath = baseUploadPath;
MultipartRequest.maxPostSize = maxPostSize;
MultipartRequest.encoding = encoding;
}
// ...
}
private void initTokenManager() {
ITokenCache tokenCache = constants.getTokenCache();
if (tokenCache != null) TokenManager.init(tokenCache);
}
TokenManager 會以「Token 最小過期時間的一半」作為間隔,啟動一個 Timer 週期性清理過期令牌:
public class TokenManager {
private static ITokenCache tokenCache;
private static Random random = new Random();
private TokenManager() {}
public static void init(ITokenCache tokenCache) {
if (tokenCache == null) return;
TokenManager.tokenCache = tokenCache;
long halfTimeOut = Const.MIN_SECONDS_OF_TOKEN_TIME_OUT * 1000 / 2;
new Timer().schedule(new TimerTask() {
public void run() { removeTimeOutToken(); }
}, halfTimeOut, halfTimeOut);
}
// ...
}
至此,JFinal 的初始化流程全部完成:容器載入 Filter → 反射建立 JFinalConfig → 配置常量、路由、外掛、攔截器與 Handler → 建構 ActionMapping 映射表 → 組裝 Handler 鏈 → 初始化渲染器、上傳元件與 Token 管理。理清這條鏈,後續排查啟動失敗或自訂擴充時就有了明確的著力點。