01: /**
02: * Copyright (C) 2006 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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: */package com.google.inject.servlet;
16:
17: import com.google.inject.Scope;
18: import com.google.inject.Provider;
19: import com.google.inject.Key;
20:
21: import javax.servlet.http.HttpServletRequest;
22: import javax.servlet.http.HttpSession;
23:
24: /**
25: * Servlet scopes.
26: *
27: * @author crazybob@google.com (Bob Lee)
28: */
29: public class ServletScopes {
30:
31: private ServletScopes() {
32: }
33:
34: /**
35: * HTTP servlet request scope.
36: */
37: public static final Scope REQUEST = new Scope() {
38: public <T> Provider<T> scope(Key<T> key,
39: final Provider<T> creator) {
40: final String name = key.toString();
41: return new Provider<T>() {
42: public T get() {
43: HttpServletRequest request = GuiceFilter
44: .getRequest();
45: synchronized (request) {
46: @SuppressWarnings("unchecked")
47: T t = (T) request.getAttribute(name);
48: if (t == null) {
49: t = creator.get();
50: request.setAttribute(name, t);
51: }
52: return t;
53: }
54: }
55: };
56: }
57:
58: public String toString() {
59: return "ServletScopes.REQUEST";
60: }
61: };
62:
63: /**
64: * HTTP session scope.
65: */
66: public static final Scope SESSION = new Scope() {
67: public <T> Provider<T> scope(Key<T> key,
68: final Provider<T> creator) {
69: final String name = key.toString();
70: return new Provider<T>() {
71: public T get() {
72: HttpSession session = GuiceFilter.getRequest()
73: .getSession();
74: synchronized (session) {
75: @SuppressWarnings("unchecked")
76: T t = (T) session.getAttribute(name);
77: if (t == null) {
78: t = creator.get();
79: session.setAttribute(name, t);
80: }
81: return t;
82: }
83: }
84: };
85: }
86:
87: public String toString() {
88: return "ServletScopes.SESSION";
89: }
90: };
91: }
|