ScalatraServlet and DyanamicVariable

12 views
Skip to first unread message

Keith Irwin

unread,
May 20, 2011, 12:14:23 PM5/20/11
to scalat...@googlegroups.com
Hi!

I'd like to store some local state between one filter and/or route match and another for the life of a single request, but I'm not sure about the lifecycle of my subclass of ScalatraServlet.

Given:

class MyApp extends ScalatraServlet {

  private var stuff = new DynamicVariable[Option[Stuff]]

  beforeAll {
     if (stuff.isEmpty)
        stuff = Some(new Stuff())
     else
        throw new NoStuffException()
  }

  get ("/*") { 
     if (stuff.get.isWhatever) {
       pass
     }
  }
}

Is MyApp instantiated anew for each incoming request? Is the implication that the MyApp class is really a request handler?

If so, does the above pattern make sense? I suppose I could also store stuff in the request itself via setAttribute, but I'd rather not.

Keith

Ivan Porto Carrero

unread,
May 20, 2011, 12:17:08 PM5/20/11
to scalat...@googlegroups.com
It's a handler, not a new instance every time
you can override the handle method for example

override protected def handle(request,response) {
   stuff.withValue(new Stuff()) {
     super.handle(request,response)
   }
}

Met vriendelijke groeten - Best regards - Salutations

Ivan Porto Carrero

Keith Irwin

unread,
May 20, 2011, 12:21:03 PM5/20/11
to scalat...@googlegroups.com
Is that the preferred way to store something across a request?

I just added a log line per request which prints out "this" and it looks like the object is the same.  object@hash-value is constant across multiple requests.

Hm.

I spose I could just read the code....

Keith Irwin

unread,
May 20, 2011, 12:26:07 PM5/20/11
to scalat...@googlegroups.com
Oh, sorry, didn't read your "not a new instance ever time" sentence. Apologies!

Ross A. Baker

unread,
May 20, 2011, 12:30:38 PM5/20/11
to scalat...@googlegroups.com
There is only one instance of MyApp. The servlet container allocates
one thread per request, which allows the DynamicVariable trick to
work.

Storing the Option inside the DynamicVariable seems unnecessary as
long as you're throwing an exception when there's no stuff. Unless
your route is going to handle None, I would simplify to
DynamicVariable[Stuff]. Request attributes are a nie option as long
as you create a getter and setter to hide the cast. Something like:

def stuff: Stuff = request("stuff").asInstanceOf[Stuff]
def stuff_=(stuff: Stuff) { request("stuff") = stuff }

--
Ross A. Baker
ba...@alumni.indiana.edu
Indianapolis, IN, USA

Reply all
Reply to author
Forward
0 new messages