1
2
3
4
5
6
7
8 package net.stff.util;
9
10 import java.io.InputStream;
11 import java.util.Hashtable;
12
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpSession;
15
16 import org.springframework.beans.factory.xml.XmlBeanFactory;
17
18 /***
19 * @author buntekuh
20 *
21 * The SessionObject stores and retrieves Beans from Spring in the Http Session. The Beans are required to implement initializable.
22 * For more information on Spring see @link http://www.springframework.org
23 *
24 */
25
26 public class SessionObject{
27 private static String KEY = "stff:SO";
28 private Hashtable table;
29
30 protected SessionObject(){
31 table= new Hashtable();
32 }
33
34
35 /***
36 * @return the key under which the SessionObject is stored in the session.
37 * Do not confuse with the keys under which the Beans are stored inside the SessionObject
38 */
39 public String getKey(){
40 return KEY;
41 }
42
43 /***
44 * @param request the current HttpServletRequest where the Session is retrieved from.
45 * @return
46 */
47 public static SessionObject get(HttpServletRequest request){
48 HttpSession session = request.getSession();
49 SessionObject sobj;
50
51 try{
52 sobj = (SessionObject) session.getAttribute(KEY);
53
54 if (sobj == null){
55 sobj = new SessionObject();
56 session.setAttribute(KEY, sobj);
57 }
58 }
59 catch (ClassCastException e){
60 return null;
61 }
62
63 return sobj;
64 }
65
66 /***
67 * Returns a bean stored in the SessionObject under the given name. If none is found,
68 * it is retrieved from the Spring applicationContext.xml file found in the classpath, instantiated and added to SessionObject.
69 * @param request The request is passed to the beans init() method, if it has not been created yet.
70 * @param key The key under which the Bean is retrieved from the Spring configuration and stored in the SessionObject.
71 * @return
72 */
73 public Initializable getObject(String key, HttpServletRequest request){
74
75 Initializable i;
76
77 i= (Initializable)table.get(key);
78 if (i != null) return i;
79
80 InputStream stream= getClass().getClassLoader().getResourceAsStream("applicationContext.xml");
81 XmlBeanFactory beanFactory= new XmlBeanFactory(stream);
82
83 try{
84 i= (Initializable)beanFactory.getBean(key);
85 }
86 catch(Exception e){
87 System.out.println(e.getMessage());
88 return null;
89 }
90
91 i.init(request);
92
93 table.put(key, i);
94 return i;
95 }
96 }