equal
deleted
inserted
replaced
|
1 package controllers |
|
2 |
|
3 import play.api._ |
|
4 import play.api.mvc._ |
|
5 import play.api.data._ |
|
6 import play.api.data.Forms._ |
|
7 |
|
8 /* |
|
9 * Application sets a cookie in plain ASCII on the |
|
10 * clients browser recording the visits of a page. |
|
11 */ |
|
12 |
|
13 object Application extends Controller { |
|
14 |
|
15 //no or invalid cookie results in the counter being 0 |
|
16 def gt_cookie(c: Option[Cookie]) : Int = c.map(_.value) match { |
|
17 case Some(s) if (s.forall(_.isDigit)) => s.toInt |
|
18 case _ => 0 |
|
19 } |
|
20 |
|
21 def mk_cookie(i: Int) : Cookie = { |
|
22 Cookie("visits", i.toString) |
|
23 } |
|
24 |
|
25 // GET request: read cookie data first |
|
26 def index = Action { request => |
|
27 |
|
28 //reads the cookie and extracts the visits counter |
|
29 val visits_cookie = request.cookies.get("visits") |
|
30 val visits = gt_cookie(visits_cookie) |
|
31 |
|
32 //printing a message according to value of visits counter |
|
33 val msg1 = "You are a valued customer who has visited this site %d times." |
|
34 val msg2 = "You have visited this site %d times." |
|
35 val msg = |
|
36 if (visits >= 10) msg1.format(visits) else msg2.format(visits) |
|
37 |
|
38 //send message with new cookie |
|
39 Ok(msg).as(HTML).withCookies(mk_cookie(visits + 1)) |
|
40 } |
|
41 } |
|
42 |
|
43 |
|
44 |
|
45 |