SparkJava Variables Scope

2019-02-19 16:45发布

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.

标签: spark-java
1条回答
劳资没心,怎么记你
2楼-- · 2019-02-19 17:39

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"
查看更多
登录 后发表回答