废话不多说,PathVariable的原理无外乎就是正则表达式了。直接上代码吧。 首先要修改 com.jfinal.core.ActionMapping , 写入一个私有属性 actionKeyList ,用来记录每个ActionKey
private final ListactionKeyList = new ArrayList ();
在 buildActionMapping 方法内加上以下代码
void buildActionMapping() { // 省略原有代码 actionKeyList.clear(); actionKeyList.addAll(mapping.keySet()); Collections.sort(actionKeyList, new Comparator() { @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } }); actionKeyList.remove("/"); actionKeyList.remove(""); }
然后就是修改 getAction 方法啦
Action getAction(String url, String[] urlPara) { Action action = mapping.get(url); if (action != null) { return action; } int i = url.lastIndexOf(SLASH); if (i != -1) { action = mapping.get(url.substring(0, i)); urlPara[0] = url.substring(i + 1); } if (action == null) { urlPara[0] = null; if (urlPara.length > 1) urlPara[1] = null; for (String actionKey : actionKeyList) { AntPathMatcher matcher = new AntPathMatcher(); if (matcher.match(actionKey, url)) { action = mapping.get(actionKey); Mapresult = matcher.extractUriTemplateVariables(actionKey, url); for (String path : new ArrayList (result.keySet())) { actionKey = actionKey.replace("{" + path + "}", result.get(path)); } if (actionKey.endsWith("/**")) actionKey = actionKey.substring(0, actionKey.length() - 4); if (url.length() > actionKey.length()) { urlPara[0] = url.substring(actionKey.length() + 1); } if (urlPara.length > 1) urlPara[1] = JSON.toJSONString(result); break; } } } return action; }
代码中主要使用了 SpringFramework 中的 AntPathMatcher,这个在SpringFramework的core包中,添加相关jar即可,或者自己剥离出来这块代码。 上面的代码里面我们扩充了urlPara的个数,相对的我们要在ActionHandler中也扩充一下urlPara的个数,并对Controller进行想对应的改造
String[] urlPara = { null, null };Action action = actionMapping.getAction(target, urlPara);// 省略代码...Controller controller = action.getControllerClass().newInstance();controller.init(request, response, urlPara[0], urlPara[1]);
用法如下
@Clear@ControllerBind(controllerKey = "testt/{uuid}")public class TestController extends Controller { public void add() { System.out.println(getPathVAriable("uuid")); renderError(404); }}