Skip to content

Instantly share code, notes, and snippets.

@BowlingX
Created October 26, 2012 10:47
Show Gist options
  • Save BowlingX/3958151 to your computer and use it in GitHub Desktop.
Save BowlingX/3958151 to your computer and use it in GitHub Desktop.
Flash Map with request Support
trait MyFlashMapSupport extends Handler {
this: CoreDsl with DynamicScope with SessionSupport =>
import FlashMapSupport._
abstract override def handle(req: HttpServletRequest, res: HttpServletResponse) {
withRequest(req) {
val f = getFlash(req)
val isOutermost = !req.contains(lockKey)
if (isOutermost) {
req(lockKey) = "locked"
if (sweepUnusedFlashEntries(req)) {
f.flag()
}
}
super.handle(req, res)
/*
* http://github.com/scalatra/scalatra/issues/41
* http://github.com/scalatra/scalatra/issues/57
*
* Only the outermost FlashMapSupport sweeps it at the end.
* This deals with both nested filters and redirects to other servlets.
*/
if (isOutermost) {
f.sweep()
}
flashMapSetSession(f)
}
}
/**
* Override to implement custom session retriever, or sanity checks if session is still active
* @param f
*/
def flashMapSetSession(f: FlashMap) {
try {
// Save flashMap to Session after (a session could stop existing during a request, so catch exception)
session(sessionKey) = f
} catch {
case e: Exception =>
}
}
/**
* Try's to receive a flashMap from current request, if it fails:
* - Try to receive map from Session orElse create a new map
* - Save this flashMap to request to maintain state
*
* @param req current request
* @return flashMap
*/
private def getFlash(req: HttpServletRequest): FlashMap = {
req.get(sessionKey).map(_.asInstanceOf[FlashMap]).getOrElse {
val map = session.get(sessionKey).map {
_.asInstanceOf[FlashMap]
}.getOrElse(new FlashMap)
req.setAttribute(sessionKey, map)
map
}
}
/**
* Returns the [[org.scalatra.FlashMap]] instance for the current request.
*/
def flash = getFlash(request)
/**
* Determines whether unused flash entries should be swept. The default is false.
*/
protected def sweepUnusedFlashEntries(req: HttpServletRequest) = false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment