progs/app2.scala
changeset 98 3d585e603927
parent 93 82ac034dcc9d
equal deleted inserted replaced
97:efcac3016613 98:3d585e603927
     1 object Application extends Controller {
     1 object Application extends Controller {
     2 
     2 
     3   def gt_cookie(c: Option[Cookie]) : Int = c.map(_.value) match {
     3   def gt_cookie(c: Cookie) : Int = c.value match {
     4     case Some(s) if (s.forall(_.isDigit)) => s.toInt 
     4     case s if (s.forall(_.isDigit)) => s.toInt 
     5     case _ => 0
     5     case _ => 0
     6   }
     6   }
     7 
     7 
     8   def mk_cookie(i: Int) : Cookie = {
     8   def mk_cookie(i: Int) : Cookie = Cookie("visits", i.toString)
     9     Cookie("visits", i.toString)
       
    10   }
       
    11   
     9   
    12   // GET request: read cookie data first
    10   // GET request: read cookie data first
    13   def index = Action { request =>
    11   def index = Action { request =>
       
    12  
       
    13     //reads the cookie and extracts the visits counter   
       
    14     val visits_cookie = request.cookies.get("visits")
       
    15     val visits = visits_cookie.map(gt_cookie).getOrElse(0)
       
    16 
       
    17     //printing a message according to value of visits counter
       
    18     val msg = 
       
    19       if (visits >= 10)
       
    20         s"You are a valued customer who has visited this site $visits times."               
       
    21       else s"You have visited this site $visits times."
    14     
    22     
    15     val visits_cookie = request.cookies.get("visits")
    23     //send message with new cookie
    16     val visits = gt_cookie(visits_cookie)
    24     Ok(msg).withCookies(mk_cookie(visits + 1))
    17 
       
    18     val msg1 = "You are a valued customer who has visited this site %d times."               
       
    19     val msg2 = "You have visited this site %d times."
       
    20     val msg = 
       
    21       if (visits >= 10) msg1.format(visits) else msg2.format(visits)
       
    22     
       
    23     //send with new cookie
       
    24     Ok(msg).as(HTML).withCookies(mk_cookie(visits + 1))
       
    25   }
    25   }
    26 }
    26 }
    27 
    27 
    28 
    28 
    29 
    29