01: /*
02: * Copyright 2005-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
05: * in compliance with the License. You may obtain a copy of the License at
06: *
07: * http://www.apache.org/licenses/LICENSE-2.0
08: *
09: * Unless required by applicable law or agreed to in writing, software distributed under the License
10: * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11: * or implied. See the License for the specific language governing permissions and limitations under
12: * the License.
13: */
14:
15: package org.strecks.injection.handler;
16:
17: import javax.servlet.http.HttpServletRequest;
18: import javax.servlet.http.HttpSession;
19:
20: import org.strecks.context.ActionContext;
21: import org.strecks.exceptions.StaleSessionException;
22: import org.strecks.util.Assert;
23: import org.strecks.util.ReflectHelper;
24:
25: /**
26: * Injection handler to find named attribute from <code>HttpSession</code>, i.e. <i>session</i>
27: * scope
28: * @author Phil Zoio
29: */
30: public class SessionAttributeInjectionHandler implements
31: InjectionHandler {
32:
33: private String attributeName;
34:
35: private Class autoCreateClass;
36:
37: private boolean required;
38:
39: public SessionAttributeInjectionHandler(String attributeName,
40: Class autoCreateClass, boolean required) {
41:
42: super ();
43: Assert.notNull(attributeName);
44: this .attributeName = attributeName;
45: this .autoCreateClass = autoCreateClass;
46: this .required = required;
47: }
48:
49: public String getAttributeName() {
50: return attributeName;
51: }
52:
53: public Object getValue(ActionContext injectionContext) {
54:
55: HttpServletRequest request = injectionContext.getRequest();
56:
57: HttpSession session = request.getSession(false);
58:
59: Object attribute = null;
60:
61: if (session != null)
62: attribute = session.getAttribute(attributeName);
63:
64: if (attribute == null) {
65: if (required) {
66: throw new StaleSessionException(
67: "Attribute missing from session: "
68: + attributeName);
69: }
70: if (autoCreateClass != null) {
71: attribute = ReflectHelper.createInstance(
72: autoCreateClass, Object.class);
73: if (session == null) {
74: session = request.getSession();
75: }
76: session.setAttribute(attributeName, attribute);
77: }
78: }
79: return attribute;
80: }
81:
82: }
|