Java Code Examples for com.jfinal.core.Controller#setAttr()

The following examples show how to use com.jfinal.core.Controller#setAttr() . 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: SessionInViewInterceptor.java    From my_curd with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: JPressInterceptor.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 3
Source File: TokenInterceptor.java    From jfinal-api-scaffold with MIT License 6 votes vote down vote up
@Override
public void intercept(ActionInvocation ai) {
    Controller controller = ai.getController();
    String token = controller.getPara("token");
    if (StringUtils.isEmpty(token)) {
        controller.renderJson(new BaseResponse(Code.ARGUMENT_ERROR, "token can not be null"));
        return;
    }

    User user = TokenManager.getMe().validate(token);
    if (user == null) {
        controller.renderJson(new BaseResponse(Code.TOKEN_INVALID, "token is invalid"));
        return;
    }
    
    controller.setAttr("user", user);
    ai.invoke();
}
 
Example 4
Source File: SearchSql.java    From my_curd with Apache License 2.0 5 votes vote down vote up
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 5
Source File: UserInterceptor.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 6
Source File: TemplateInterceptor.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 7
Source File: ArticleModuleInitializer.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String onRenderDashboardBox(Controller controller) {
    List<Article> articles = Aop.get(ArticleService.class).findListByColumns(Columns.create().eq("status", Article.STATUS_NORMAL), "id desc", 10);
    controller.setAttr("articles", articles);

    ArticleCommentService commentService = Aop.get(ArticleCommentService.class);
    List<ArticleComment> articleComments = commentService.findListByColumns(Columns.create().ne("status", ArticleComment.STATUS_TRASH), "id desc", 10);
    controller.setAttr("articleComments", articleComments);

    return "article/_dashboard_box.html";
}
 
Example 8
Source File: ProductValidate.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 9
Source File: PayConfigUtil.java    From jpress with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void setConfigAttrs(Controller controller) {
    controller.setAttr("alipayConfig", getAlipayPayConfig());
    controller.setAttr("alipayxConfig", getAlipayxPayConfig());
    controller.setAttr("wechatConfig", getWechatPayConfig());
    controller.setAttr("wechatxConfig", getWechatxPayConfig());
    controller.setAttr("paypalConfig", getPaypalPayConfig());
}
 
Example 10
Source File: VisitorInterceptor.java    From zrlog with Apache License 2.0 5 votes vote down vote up
/**
 * 方便开发环境使用,将Servlet的Request域的数据转化JSON字符串,配合dev.jsp使用,定制主题更加方便
 *
 * @param controller
 */
private void fullDevData(Controller controller) {
    boolean dev = JFinal.me().getConstants().getDevMode();
    controller.setAttr("dev", dev);
    if (dev) {
        Map<String, Object> attrMap = new LinkedHashMap<>();
        Enumeration<String> enumerations = controller.getAttrNames();
        while (enumerations.hasMoreElements()) {
            String key = enumerations.nextElement();
            attrMap.put(key, controller.getAttr(key));
        }
        controller.setAttr("requestScopeJsonString", Json.getJson().toJson(attrMap));
    }
}
 
Example 11
Source File: AdminInterceptor.java    From zrlog with Apache License 2.0 5 votes vote down vote up
/**
 * 为了规范代码,这里做了一点类是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: CacheService.java    From zrlog with Apache License 2.0 4 votes vote down vote up
private void initCache(Controller baseController) {
    BaseDataInitVO cacheInit = (BaseDataInitVO) JFinal.me().getServletContext().getAttribute(Constants.CACHE_KEY);
    if (cacheInit == null) {
        cacheInit = new BaseDataInitVO();
        Map<String, Object> website = new WebSite().getWebSite();
        //兼容早期模板判断方式
        website.put("user_comment_pluginStatus", "on".equals(website.get("duoshuo_status")));

        BaseDataInitVO.Statistics statistics = new BaseDataInitVO.Statistics();
        statistics.setTotalArticleSize(new Log().count());
        cacheInit.setStatistics(statistics);
        cacheInit.setWebSite(website);
        cacheInit.setLinks(new Link().find());
        cacheInit.setTypes(new Type().find());
        statistics.setTotalTypeSize(cacheInit.getTypes().size());
        cacheInit.setLogNavs(new LogNav().find());
        cacheInit.setPlugins(new Plugin().find());
        cacheInit.setArchives(new Log().getArchives());
        cacheInit.setTags(new Tag().find());
        statistics.setTotalTagSize(cacheInit.getTags().size());
        List<Type> types = cacheInit.getTypes();
        cacheInit.setHotLogs((List<Log>) new Log().find(1, 6).get("rows"));
        Map<Map<String, Object>, List<Log>> indexHotLog = new LinkedHashMap<>();
        for (Type type : types) {
            Map<String, Object> typeMap = new TreeMap<>();
            typeMap.put("typeName", type.getStr("typeName"));
            typeMap.put("alias", type.getStr("alias"));
            indexHotLog.put(typeMap, (List<Log>) new Log().findByTypeAlias(1, 6, type.getStr("alias")).get("rows"));
        }
        cacheInit.setIndexHotLogs(indexHotLog);
        //存放公共数据到ServletContext
        JFinal.me().getServletContext().setAttribute("WEB_SITE", website);
        JFinal.me().getServletContext().setAttribute(Constants.CACHE_KEY, cacheInit);
        List<File> staticFiles = new ArrayList<>();
        FileUtils.getAllFiles(PathKit.getWebRootPath(), staticFiles);
        for (File file : staticFiles) {
            String uri = file.toString().substring(PathKit.getWebRootPath().length());
            cacheFileMap.put(uri, file.lastModified() + "");
        }
    }
    if (baseController != null) {
        final BaseDataInitVO cacheInitFile = cacheInit;
        if(cacheInit.getTags() == null || cacheInit.getTags().isEmpty()){
            cacheInit.getPlugins().stream().filter(e -> e.get("pluginName").equals("tags")).findFirst().ifPresent(e -> {
                cacheInitFile.getPlugins().remove(e);
            });
        }
        if(cacheInit.getArchives() == null || cacheInit.getArchives().isEmpty()){
            cacheInit.getPlugins().stream().filter(e -> e.get("pluginName").equals("archives")).findFirst().ifPresent(e -> {
                cacheInitFile.getPlugins().remove(e);
            });
        }
        if(cacheInit.getTypes() == null || cacheInit.getTypes().isEmpty()){
            cacheInit.getPlugins().stream().filter(e -> e.get("pluginName").equals("types")).findFirst().ifPresent(e -> {
                cacheInitFile.getPlugins().remove(e);
            });
        }
        if(cacheInit.getLinks() == null || cacheInit.getLinks().isEmpty()){
            cacheInit.getPlugins().stream().filter(e -> e.get("pluginName").equals("links")).findFirst().ifPresent(e -> {
                cacheInitFile.getPlugins().remove(e);
            });
        }
        baseController.setAttr("init", cacheInitFile);
        baseController.setAttr("website", cacheInitFile.getWebSite());
        //默认开启文章封面
        cacheInitFile.getWebSite().putIfAbsent("article_thumbnail_status", "1");
        Constants.WEB_SITE.clear();
        Constants.WEB_SITE.putAll(cacheInitFile.getWebSite());
    }
}