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 java.io.IOException;
18:
19: import javax.servlet.Filter;
20: import javax.servlet.FilterChain;
21: import javax.servlet.FilterConfig;
22: import javax.servlet.ServletException;
23: import javax.servlet.ServletRequest;
24: import javax.servlet.ServletResponse;
25: import javax.servlet.http.HttpServletRequest;
26: import javax.servlet.http.HttpServletResponse;
27:
28: /**
29: * Apply this filter to all requests where you plan to use servlet scopes.
30: *
31: * @author crazybob@google.com (Bob Lee)
32: */
33: public class GuiceFilter implements Filter {
34:
35: static final ThreadLocal<Context> localContext = new ThreadLocal<Context>();
36:
37: public void doFilter(ServletRequest servletRequest,
38: ServletResponse servletResponse, FilterChain filterChain)
39: throws IOException, ServletException {
40: Context previous = localContext.get();
41: try {
42: localContext.set(new Context(
43: (HttpServletRequest) servletRequest,
44: (HttpServletResponse) servletResponse));
45: filterChain.doFilter(servletRequest, servletResponse);
46: } finally {
47: localContext.set(previous);
48: }
49: }
50:
51: static HttpServletRequest getRequest() {
52: return getContext().getRequest();
53: }
54:
55: static HttpServletResponse getResponse() {
56: return getContext().getResponse();
57: }
58:
59: static Context getContext() {
60: Context context = localContext.get();
61: if (context == null) {
62: throw new RuntimeException("Please apply "
63: + GuiceFilter.class.getName()
64: + " to any request which uses servlet scopes.");
65: }
66: return context;
67: }
68:
69: static class Context {
70:
71: final HttpServletRequest request;
72: final HttpServletResponse response;
73:
74: Context(HttpServletRequest request, HttpServletResponse response) {
75: this .request = request;
76: this .response = response;
77: }
78:
79: HttpServletRequest getRequest() {
80: return request;
81: }
82:
83: HttpServletResponse getResponse() {
84: return response;
85: }
86: }
87:
88: public void init(FilterConfig filterConfig) throws ServletException {
89: }
90:
91: public void destroy() {
92: }
93: }
|