@Override public void configInterceptor(Interceptors me) { //添加控制层全局拦截器 me.addGlobalActionInterceptor(new AuthInterceptor()); me.add(new TxByMethodRegex("(.*save.*|.*update.*)")); /*me.add(new TxByMethods("save", "update"));*/ /*me.add(new TxByActionKeyRegex(".*trans.*|.*save.*"));*/ /*me.add(new TxByActionKeys("/tx/save", "/tx/update"));*/ //session拦截器,用于在View模板中取出session值 me.addGlobalActionInterceptor(new SessionInViewInterceptor(true)); //添加异常和日志拦截器 me.addGlobalActionInterceptor(new ExceptionAndLogInterceptor(".*trans.*|.*save.*")); } public class ExceptionAndLogInterceptor extends com.jfinal.ext.interceptor.LogInterceptor { private Pattern pattern; public ExceptionAndLogInterceptor(String regex){ this(regex,true); } public ExceptionAndLogInterceptor(String regex,boolean caseSensitive){ if(StrKit.isBlank(regex)) { throw new IllegalArgumentException("regex can not be blank."); } else { this.pattern = caseSensitive?Pattern.compile(regex):Pattern.compile(regex, 2); } } public void intercept(Invocation invocation){ Controller controller = invocation.getController(); HttpServletRequest request = controller.getRequest(); invocation.invoke(); if(this.pattern.matcher(invocation.getActionKey()).matches()) { TUser user = controller.getSessionAttr("user"); LogKit.info("当前用户:"+user.getUsername()); TLog log = new TLog(); log.setId(StrKit.getRandomUUID()); log.setActionkey(invocation.getActionKey()); log.setOpertime(DateKit.toStr(new Date(),DateKit.timeFormat)); log.setUserid(user.getId()); log.setUsername(user.getUsername()); log.setIp(ConvertKit.getRemoteHost(request)); log.setParams(JFinalJson.getJson().toJson(request.getParameterMap())); log.setResult(JFinalJson.getJson().toJson(controller.getRender())); log.save(); } } }
controller 与 request 的获取建议放在 if 分支里头,可节省点时空