SparkJava Variables Scope

风流意气都作罢 提交于 2019-12-01 07:37:56

问题


I'm developing a SparkJava (not Apache Spark) app, and I'd like to share an object between a before filter and a post route. The filter and the route are defined in different classes. I'm not willing to go on with sessions, cause it's a mobile app json api and theoretically speaking, it should be session free. The variable scope should be from the beginning of the request handling until the end.

    before(Main.API_PROTECTED + "/*", (req, res) -> {
        String token = req.headers("Authorization");
        if (token == null | "".equals(token)) {
            halt(401, "You're not welcome.");
        } else {
            Partner partner = new PartnerDAO().getPartnerByToken(token.replace("Bearer ", ""));
            if (partner == null) {
                halt(401, "You're not welcome.");
            }
        }
    });

There's the above before filter, from which I'd like to share the partner object with the post route below:

        post(Main.API_PROTECTED + "/vendors",
            (req, res) -> {
                // Do stuff to insert Vendors in the Database, verifying access control using the partner object
                return "";
            });

Maybe in the future, the app will need to scale, so keep in mind that there may be more than one node running this.


回答1:


Add the object to the request in the filter.

 request.attribute("myObject", "my value");

Look it up in the post

request.attribute("myObject");  // "my value"


来源:https://stackoverflow.com/questions/33069768/sparkjava-variables-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!