KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > google > inject > servlet > ServletScopes


1 /**
2  * Copyright (C) 2006 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package com.google.inject.servlet;
18
19 import com.google.inject.Scope;
20 import com.google.inject.Provider;
21 import com.google.inject.Key;
22
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpSession JavaDoc;
25
26 /**
27  * Servlet scopes.
28  *
29  * @author crazybob@google.com (Bob Lee)
30  */

31 public class ServletScopes {
32
33   private ServletScopes() {}
34
35   /**
36    * HTTP servlet request scope.
37    */

38   public static final Scope REQUEST = new Scope() {
39     public <T> Provider<T> scope(Key<T> key, final Provider<T> creator) {
40       final String JavaDoc name = key.toString();
41       return new Provider<T>() {
42         public T get() {
43           HttpServletRequest JavaDoc request = GuiceFilter.getRequest();
44           synchronized (request) {
45             @SuppressWarnings JavaDoc("unchecked")
46             T t = (T) request.getAttribute(name);
47             if (t == null) {
48               t = creator.get();
49               request.setAttribute(name, t);
50             }
51             return t;
52           }
53         }
54       };
55     }
56
57     public String JavaDoc toString() {
58       return "ServletScopes.REQUEST";
59     }
60   };
61
62   /**
63    * HTTP session scope.
64    */

65   public static final Scope SESSION = new Scope() {
66     public <T> Provider<T> scope(Key<T> key, final Provider<T> creator) {
67       final String JavaDoc name = key.toString();
68       return new Provider<T>() {
69         public T get() {
70           HttpSession JavaDoc session = GuiceFilter.getRequest().getSession();
71           synchronized (session) {
72             @SuppressWarnings JavaDoc("unchecked")
73             T t = (T) session.getAttribute(name);
74             if (t == null) {
75               t = creator.get();
76               session.setAttribute(name, t);
77             }
78             return t;
79           }
80         }
81       };
82     }
83
84     public String JavaDoc toString() {
85       return "ServletScopes.SESSION";
86     }
87   };
88 }
89
Popular Tags