Java Code Examples for com.jfinal.aop.Invocation#getController()
The following examples show how to use
com.jfinal.aop.Invocation#getController() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NotNullParaInterceptor.java From jboot-admin with Apache License 2.0 | 6 votes |
private void renderError(Invocation inv, String param, String errorRedirect) { if (StrUtils.isNotBlank(errorRedirect)) { inv.getController().redirect(errorRedirect); return; } Controller controller = inv.getController(); if (controller instanceof JbootController) { JbootController jc = (JbootController) controller; if (jc.isAjaxRequest()) { jc.renderJson(RestResult.buildError("参数["+param+"]不可为空")); return; } } controller.setAttr(BusinessExceptionInterceptor.MESSAGE_TAG, "参数["+param+"]不可为空").render(exceptionView); }
Example 2
Source File: IocInterceptor.java From jfinal-ext3 with Apache License 2.0 | 6 votes |
public void intercept(Invocation ai) { Controller controller = ai.getController(); Field[] fields = controller.getClass().getDeclaredFields(); for (Field field : fields) { Object bean = null; if (field.isAnnotationPresent(Inject.BY_NAME.class)) bean = ctx.getBean(field.getName()); else if (field.isAnnotationPresent(Inject.BY_TYPE.class)) bean = ctx.getBean(field.getType()); else continue ; try { if (bean != null) { field.setAccessible(true); field.set(controller, bean); } } catch (Exception e) { throw new RuntimeException(e); } } ai.invoke(); }
Example 3
Source File: ParaValidateInterceptor.java From jboot with Apache License 2.0 | 6 votes |
/** * 对验证码进行验证 * * @param inv * @param captchaValidate * @return */ private boolean validateCaptache(Invocation inv, CaptchaValidate captchaValidate) { String formName = AnnotationUtil.get(captchaValidate.form()); if (StrUtil.isBlank(formName)) { throw new IllegalArgumentException("@CaptchaValidate.form must not be empty in " + inv.getController().getClass().getName() + "." + inv.getMethodName()); } Controller controller = inv.getController(); if (controller.validateCaptcha(formName)) { return true; } renderError(inv.getController() , AnnotationUtil.get(captchaValidate.renderType()) , formName , AnnotationUtil.get(captchaValidate.message()) , AnnotationUtil.get(captchaValidate.redirectUrl()) , AnnotationUtil.get(captchaValidate.htmlPath()) , captchaValidate.errorCode() ); return false; }
Example 4
Source File: WechatUserInterceptor.java From jboot with Apache License 2.0 | 6 votes |
@Override public void intercept(Invocation inv) { JbootWechatController controller = (JbootWechatController) inv.getController(); /** * 是否允许访问,默认情况下只有是微信浏览器允许访问 */ if (controller.isAllowVisit()) { doIntercept(inv); return; } controller.doNotAlloVisitRedirect(); }
Example 5
Source File: WechatApiConfigInterceptor.java From jboot with Apache License 2.0 | 6 votes |
@Override public void intercept(Invocation inv) { try { JbootWechatController controller = (JbootWechatController) inv.getController(); ApiConfig config = controller.getApiConfig(); if (config == null) { inv.getController().renderText("error : cannot get apiconfig,please config jboot.properties"); return; } ApiConfigKit.setThreadLocalAppId(config.getAppId()); inv.invoke(); } finally { ApiConfigKit.removeThreadLocalAppId(); } }
Example 6
Source File: LimitFallbackProcesserDefault.java From jboot with Apache License 2.0 | 6 votes |
/** * 处理 Controller 的限流 * * @param resource * @param inv */ protected void doProcessWebLimit(String resource, Invocation inv) { Controller controller = inv.getController(); controller.getResponse().setStatus(config.getDefaultHttpCode()); if (RequestUtil.isAjaxRequest(controller.getRequest())) { controller.renderJson(config.getDefaultAjaxContent()); } //非ajax的正常请求 else { String limitView = config.getDefaultHtmlView(); if (limitView != null) { controller.render(limitView); } else { controller.renderText("reqeust limit."); } } }
Example 7
Source File: VisitLogInterceptor.java From my_curd with Apache License 2.0 | 6 votes |
@Override public void intercept(Invocation inv) { Controller controller = inv.getController(); SysVisitLog sysVisitLog = new SysVisitLog(); sysVisitLog.setId(IdUtils.id()); sysVisitLog.setSysUserIp(WebUtils.getRemoteAddress(controller.getRequest())); sysVisitLog.setSysUser(WebUtils.getSessionUsername(controller)); sysVisitLog.setUrl(inv.getActionKey()); sysVisitLog.setRequestType(controller.getRequest().getMethod()); sysVisitLog.setCreateTime(new Date()); Map<String, String[]> params = controller.getRequest().getParameterMap(); if (params.keySet().size() > 0) { sysVisitLog.setParam(JSON.toJSONString(params)); // if (sysVisitLog.getParam().length() > 100) { // sysVisitLog.setParam("超长文本参数"); // } } sysVisitLog.save(); inv.invoke(); }
Example 8
Source File: SessionInViewInterceptor.java From my_curd with Apache License 2.0 | 6 votes |
@SuppressWarnings({"rawtypes", "unchecked"}) public void intercept(Invocation inv) { inv.invoke(); Controller c = inv.getController(); if (c.getRender() instanceof com.jfinal.render.JsonRender) { return; } HttpSession hs = c.getSession(false); if (hs != null) { Map session = new com.jfinal.ext.interceptor.SessionInViewInterceptor.JFinalSession(hs); for (String sessionField : sessionFields) { session.put(sessionField, hs.getAttribute(sessionField)); } c.setAttr("session", session); } }
Example 9
Source File: JPressInterceptor.java From jpress with GNU Lesser General Public License v3.0 | 6 votes |
@Override public void intercept(Invocation inv) { Controller controller = inv.getController(); //方便模板开发者直接在模板里接收参数 controller.setAttr("C", controller); controller.setAttr("CDN", JPressOptions.getCDNDomain()); controller.setAttr(ADDON_PATH_KEY, ADDON_PATH_VALUE); Enumeration<String> paraKeys = controller.getParaNames(); if (paraKeys != null) { while (paraKeys.hasMoreElements()) { String key = paraKeys.nextElement(); // 有很多 options 字段的 model,为了扩展 model 本身的内容 // 为了安全起见,不让客户端提交 .options 对 model 本身的 options 字段进行覆盖 if (key != null && key.endsWith(".options")) { LogKit.error("paras has options key :" + key); controller.renderError(404); return; } } } inv.invoke(); }
Example 10
Source File: MsgInterceptor.java From jfinal-weixin with Apache License 2.0 | 5 votes |
public void intercept(Invocation inv) { Controller controller = inv.getController(); if (controller instanceof MsgController == false) throw new RuntimeException("控制器需要继承 MsgController"); try { // 将 ApiConfig 对象与当前线程绑定,以便在后续操作中方便获取该对象: ApiConfigKit.getApiConfig(); ApiConfigKit.setThreadLocalApiConfig(((MsgController)controller).getApiConfig()); // 如果是服务器配置请求,则配置服务器并返回 if (isConfigServerRequest(controller)) { configServer(controller); return ; } // 对开发测试更加友好 if (ApiConfigKit.isDevMode()) { inv.invoke(); } else { // 如果是服务器配置请求,则配置服务器并返回 if (isConfigServerRequest(controller)) { configServer(controller); return ; } // 签名检测 if (checkSignature(controller)) { inv.invoke(); } else { controller.renderText("签名验证失败,请确定是微信服务器在发送消息过来"); } } } finally { ApiConfigKit.removeThreadLocalApiConfig(); } }
Example 11
Source File: AdminInterceptor.java From zrlog with Apache License 2.0 | 5 votes |
/** * 为了规范代码,这里做了一点类是Spring的ResponseEntity的东西,及通过方法的返回值来判断是应该返回页面还会对应JSON数据 * 具体方式看 AdminRouters,这里用到了 ThreadLocal * * @param ai */ private void adminPermission(Invocation ai) { Controller controller = ai.getController(); AdminTokenVO adminTokenVO = adminTokenService.getAdminTokenVO(controller.getRequest()); if (adminTokenVO != null) { try { User user = new User().findById(adminTokenVO.getUserId()); if (StringUtils.isEmpty(user.getStr("header"))) { user.set("header", Constants.DEFAULT_HEADER); } controller.setAttr("user", user); controller.setAttr("protocol", adminTokenVO.getProtocol()); TemplateHelper.fullTemplateInfo(controller, false); if (!"/admin/logout".equals(ai.getActionKey())) { adminTokenService.setAdminToken(user, adminTokenVO.getSessionId(), adminTokenVO.getProtocol(), controller.getRequest(), controller.getResponse()); } ai.invoke(); // 存在消息提示 if (controller.getAttr("message") != null) { initIndex(controller.getRequest()); controller.render(new FreeMarkerRender("/admin/index.ftl")); } else { if (!tryDoRender(ai, controller)) { controller.renderHtml(IOUtil.getStringInputStream(new FileInputStream(PathKit.getWebRootPath() + Constants.NOT_FOUND_PAGE))); } } } catch (Exception e) { LOGGER.error("", e); exceptionHandler(ai, e); } finally { AdminTokenThreadLocal.remove(); } } else if ("/admin/login".equals(ai.getActionKey()) || "/api/admin/login".equals(ai.getActionKey())) { ai.invoke(); tryDoRender(ai, controller); } else { blockUnLoginRequestHandler(ai); } }
Example 12
Source File: ApiInterceptor.java From jfinal-weixin with Apache License 2.0 | 5 votes |
public void intercept(Invocation inv) { Controller controller = inv.getController(); if (controller instanceof ApiController == false) throw new RuntimeException("控制器需要继承 ApiController"); try { ApiConfigKit.setThreadLocalApiConfig(((ApiController)controller).getApiConfig()); inv.invoke(); } finally { ApiConfigKit.removeThreadLocalApiConfig(); } }
Example 13
Source File: ProductValidate.java From jpress with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void intercept(Invocation inv) { Controller c = inv.getController(); Long productId = inv.getController().getLong("id"); Product product = productService.findById(productId); if (product == null || !product.isNormal()) { if (RequestUtil.isAjaxRequest(c.getRequest())) { c.renderJson(Ret.fail().set("code", "2").set("message", "商品不存在或已下架。")); } else { c.renderError(404); } return; } User user = UserInterceptor.getThreadLocalUser(); if (user == null) { if (RequestUtil.isAjaxRequest(c.getRequest())) { c.renderJson(Ret.fail() .set("code", 1) .set("message", "用户未登录") .set("gotoUrl", JFinal.me().getContextPath() + "/user/login?gotoUrl=" + product.getUrl())); } else { c.redirect("/user/login?gotoUrl=" + product.getUrl()); } return; } c.setAttr(ATTR_PRODUCT,product); inv.invoke(); }
Example 14
Source File: TemplateInterceptor.java From jpress with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void intercept(Invocation inv) { Controller controller = inv.getController(); controller.setAttr(JPressConsts.ATTR_WEB_TITLE, StrUtil.escapeHtml(webTitle)); controller.setAttr(JPressConsts.ATTR_WEB_SUBTITLE, StrUtil.escapeHtml(webSubTitle)); controller.setAttr(JPressConsts.ATTR_WEB_NAME, StrUtil.escapeHtml(webName)); controller.setAttr(JPressConsts.ATTR_WEB_IPC_NO, StrUtil.escapeHtml(webIpcNo)); controller.setAttr(JPressConsts.ATTR_SEO_TITLE, StrUtil.escapeHtml(seoTitle)); controller.setAttr(JPressConsts.ATTR_SEO_KEYWORDS, StrUtil.escapeHtml(seoKeyword)); controller.setAttr(JPressConsts.ATTR_SEO_DESCRIPTION, StrUtil.escapeHtml(seoDescription)); controller.setAttr(JPressConsts.ATTR_WEB_DOMAIN, webDomain); controller.setAttr(JPressConsts.ATTR_WEB_COPYRIGHT, webCopyright); //添加CSRF的配置,方便在前台进行退出等操作 String uuid = StrUtil.uuid(); inv.getController().setCookie(CSRFInterceptor.CSRF_KEY, uuid, -1); inv.getController().setAttr(CSRFInterceptor.CSRF_ATTR_KEY, uuid); MenuService menuService = Aop.get(MenuService.class); List<Menu> menus = menuService.findListByType(Menu.TYPE_MAIN); SortKit.toTree(menus); controller.setAttr(JPressConsts.ATTR_MENUS, menus); Template template = TemplateManager.me().getCurrentTemplate(); controller.setAttr("TPATH", template == null ? "" : template.getRelativePath()); inv.invoke(); }
Example 15
Source File: UserInterceptor.java From jpress with GNU Lesser General Public License v3.0 | 5 votes |
@Override public void intercept(Invocation inv) { Controller c = inv.getController(); User user = c.getAttr(JPressConsts.ATTR_LOGINED_USER); if (user != null) { //购物车的相关信息 setUserCartInfoAttrs(inv, user); inv.invoke(); return; } String uid = CookieUtil.get(c, JPressConsts.COOKIE_UID); if (StrUtil.isBlank(uid)) { inv.invoke(); return; } user = userService.findById(uid); if (user != null) { c.setAttr(JPressConsts.ATTR_LOGINED_USER, user); setUserCartInfoAttrs(inv, user); } inv.invoke(); }
Example 16
Source File: PermissionInterceptor.java From my_curd with Apache License 2.0 | 5 votes |
@Override public void intercept(Invocation inv) { boolean flag = true; Controller controller = inv.getController(); // 验证菜单权限 RequirePermission requirePermission = inv.getClass().getAnnotation(RequirePermission.class); List<String> codes; if (requirePermission != null ) { codes = requirePermission.isPermission() ? controller.getSessionAttr("menuCodes") : controller.getSessionAttr("roleCodes"); flag = codes.contains(requirePermission.value()); } if (flag) { // 菜单权限通后 再验证按钮权限 requirePermission = inv.getMethod().getAnnotation(RequirePermission.class); if (requirePermission != null) { codes = requirePermission.isPermission() ? controller.getSessionAttr("buttonCodes") : controller.getSessionAttr("roleCodes"); flag = codes.contains(requirePermission.value()); } } if (flag) { // 菜单权限、按钮权限 都具备 放行 inv.invoke(); return; } // 无权限响应 String requestType = inv.getController().getHeader("X-Requested-With"); if ("XMLHttpRequest".equals(requestType) || StringUtils.notEmpty(inv.getController().getPara("xmlHttpRequest"))) { Ret ret = Ret.create().setFail().set("msg", "无权限操作!您的行为已被记录到日志。"); // 其实并没有,可以自行扩展 controller.renderJson(ret); } else { controller.render("/WEB-INF/views/common/no_permission.ftl"); } }
Example 17
Source File: SearchSql.java From my_curd with Apache License 2.0 | 5 votes |
public void intercept(Invocation ai) { Controller c = ai.getController(); // 查询字段前缀 String prefix = "search_"; // 获得 查询 参数 Map<String, Object> searchParams = getParametersStartingWith(c.getRequest(), prefix); // 获得 查询 所有的 查询 filter Map<String, SearchFilter> filters = SearchFilter.parse(searchParams); // 根据 filter 获得 wheresql 语句 String whereSql = buildFilter(filters.values()); c.setAttr(Constant.SEARCH_SQL, whereSql); int pageNumber = c.getParaToInt("page", 1); int pageSize = c.getParaToInt("rows", 1); //分页参数, 兼容 bootstrap 分页 和 easyui grid 分页 // int pageNumber; // int pageSize; // if (StrKit.notBlank(c.getPara("offset"))) { // // bootstraptable 分页 // pageNumber = c.getParaToInt("offset", 0); // pageSize = c.getParaToInt("limit", 10); // if (pageNumber != 0) {// 获取页数 // pageNumber = pageNumber / pageSize; // } // pageNumber += 1; // } else { // // easyui grid 分页 // pageNumber = c.getParaToInt("page", 1); // pageSize = c.getParaToInt("rows", 1); // } c.setAttr("pageNumber", pageNumber); c.setAttr("pageSize", pageSize); ai.invoke(); }
Example 18
Source File: UTMInterceptor.java From jpress with GNU Lesser General Public License v3.0 | 4 votes |
private void doRecordUTM(Invocation inv) { Controller controller = inv.getController(); Utm utm = new Utm(); utm.setId(StrUtil.uuid()); utm.setActionKey(controller.getRequest().getRequestURI()); utm.setActionQuery(controller.getRequest().getQueryString()); utm.setIp(RequestUtil.getIpAddress(controller.getRequest())); utm.setAgent(RequestUtil.getUserAgent(controller.getRequest())); utm.setReferer(RequestUtil.getReferer(controller.getRequest())); String uid = CookieUtil.get(controller, JPressConsts.COOKIE_UID); if (StrUtil.isNotBlank(uid)) { utm.setUserId(Long.valueOf(uid)); } /** * 可能是API的用户,API 通过 jwt 获取用户信息 */ else if (controller instanceof JbootController) { JbootController c = (JbootController) controller; Number userId = c.getJwtPara(JPressConsts.JWT_USERID); if (userId != null) { utm.setUserId(userId.longValue()); } } /** * 当用户未登录的情况下,创建匿名记录 */ else { //anonym String anonym = CookieUtil.get(controller, JPressConsts.COOKIE_ANONYM); if (StrUtil.isNotBlank(anonym)) { utm.setAnonym(anonym); } else { CookieUtil.put(controller, JPressConsts.COOKIE_ANONYM, StrUtil.uuid(), 60 * 60 * 24 * 365); } } utm.setSource(controller.getPara("source")); utm.setMedium(controller.getPara("medium")); utm.setCampaign(controller.getPara("campaign")); utm.setContent(controller.getPara("content")); utm.setTerm(controller.getPara("term")); utmService.doRecord(utm); }
Example 19
Source File: ApiInterceptor.java From jpress with GNU Lesser General Public License v3.0 | 4 votes |
@Override public void intercept(Invocation inv) { // API 功能未启用 if (apiEnable == false) { inv.getController().renderJson(Ret.fail().set("message", "API功能已经关闭,请管理员在后台进行开启")); return; } if (StrUtil.isBlank(apiAppId)) { inv.getController().renderJson(Ret.fail().set("message", "后台配置的 APP ID 不能为空,请先进入后台的接口管理进行配置。")); return; } if (StrUtil.isBlank(apiSecret)) { inv.getController().renderJson(Ret.fail().set("message", "后台配置的 API 密钥不能为空,请先进入后台的接口管理进行配置。")); return; } JbootController controller = (JbootController) inv.getController(); String queryString = controller.getRequest().getQueryString(); if (StrUtil.isBlank(queryString)) { inv.getController().renderJson(Ret.fail().set("message", "请求参数错误。")); return; } Map<String, String> parasMap = paramToMap(queryString); String appId = parasMap.get("appId"); if (StrUtil.isBlank(appId)) { inv.getController().renderJson(Ret.fail().set("message", "在Url中未获取到appId内容,请注意Url是否正确。")); return; } if (!appId.equals(apiAppId)) { inv.getController().renderJson(Ret.fail().set("message", "客户端配置的AppId和服务端配置的不一致。")); return; } String sign = parasMap.get("sign"); if (StrUtil.isBlank(sign)) { controller.renderJson(Ret.fail("message", "签名数据不能为空,请提交 sign 数据。")); return; } String timeStr = parasMap.get("t"); Long time = timeStr == null ? null : Long.valueOf(timeStr); if (time == null) { controller.renderJson(Ret.fail("message", "时间参数不能为空,请提交 t 参数数据。")); return; } // 时间验证,可以防止重放攻击 if (Math.abs(System.currentTimeMillis() - time) > TIMEOUT) { controller.renderJson(Ret.fail("message", "请求超时,请重新请求。")); return; } String localSign = createLocalSign(controller); if (sign.equals(localSign) == false) { inv.getController().renderJson(Ret.fail().set("message", "数据签名错误。")); return; } Object userId = controller.getJwtPara(JPressConsts.JWT_USERID); if (userId != null) { controller.setAttr(JPressConsts.ATTR_LOGINED_USER, userService.findById(userId)); } inv.invoke(); }
Example 20
Source File: JwtInterceptor.java From jboot with Apache License 2.0 | 4 votes |
private void processInvoke(Invocation inv, Map oldData) { inv.invoke(); if (!(inv.getController() instanceof JbootController)) { return; } JbootController jbootController = (JbootController) inv.getController(); Map<String, Object> jwtMap = jbootController.getJwtAttrs(); if (jwtMap == null || jwtMap.isEmpty()) { refreshIfNecessary(inv, oldData); return; } String token = JwtManager.me().createJwtToken(jwtMap); HttpServletResponse response = inv.getController().getResponse(); response.addHeader(JwtManager.me().getHttpHeaderName(), token); }