--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/progs/Application2.scala Tue Sep 24 12:23:54 2013 +0100
@@ -0,0 +1,43 @@
+package controllers
+
+import play.api.mvc._
+
+/*
+ * Application sets a cookie in plain ASCII on the
+ * client's browser recording the number of visits
+ * of a page.
+ */
+
+object Application extends Controller {
+
+ //no or invalid cookie results in the counter being 0
+ def gt_cookie(c: Cookie) : Int = c.value match {
+ case s if (s.forall(_.isDigit)) => s.toInt
+ case _ => 0
+ }
+
+ def mk_cookie(i: Int) : Cookie = {
+ Cookie("visits", i.toString)
+ }
+
+ // GET request: read cookie data first
+ def index = Action { request =>
+
+ //reads the cookie and extracts the visits counter
+ val visits_cookie = request.cookies.get("visits")
+ val visits = visits_cookie.map(gt_cookie).getOrElse(0)
+
+ //printing a message according to value of visits counter
+ val msg =
+ if (visits >= 10)
+ s"You are a valued customer who has visited this site $visits times."
+ else s"You have visited this site $visits times."
+
+ //send message with new cookie
+ Ok(msg).withCookies(mk_cookie(visits + 1))
+ }
+}
+
+
+
+