Set Groovlet session object within a class?

866 Views Asked by At

I have a Groovy class, MyRequest, that is used to process each HTTP request. In the constructor, this class sets an instance variable, _session, to be the value of request.getSession(true) (where request is the current HttpServletRequest).

In my Groovy script, the first thing I do is create an instance of MyRequest. Second, I check for a specific property of the Groovlet session object. With my first request to the script, this session object is null so I get a null object reference error. The second request to the script, the session object is defined and no error occurs.

According to the Groovlet documentation, this situation should be expected because I did not explicitly set the Groovlet's session object after checking for its existence in my script.

I really don't want to have to add yet more copy an paste code to my scripts (and any future ones in the project). This is one of the reasons I created the MyRequest object -- to define the session object for any script that instantiates it. So, how can I define the session object for my Groovy scripts within the MyRequest class? Can I use the metaClass object in some way?

1

There are 1 best solutions below

5
virtualeyes On

Groovlets provide session scope for you out of the box, no need for request.getSession().

If from your script you do:

new MyRequest(session)

then given a sloppy, untyped MyRequest class like so:

class MyRequest {
    def _session
    MyRequest(sess) {
        _session = sess
    }

    def nullSafe() {
        if(_sess?.notExist) // do something...
    }
}

MyRequest methods can refer to session safely (provided you use groovy null safe (?) operator). I have moved away from Groovlets, but when I was rolling my own, Groovy gurus suggested using Thread locals when passing session, request, response et al from script scope to objects...