KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jodd > bean > loader > ServletContextBeanLoader


1 // Copyright (c) 2003-2007, Jodd Team (jodd.sf.net). All Rights Reserved.
2

3 package jodd.bean.loader;
4
5 import java.util.Enumeration JavaDoc;
6
7 import javax.servlet.ServletContext JavaDoc;
8
9 import jodd.bean.BeanUtil;
10 import jodd.bean.BeanException;
11
12 /**
13  * Populates java bean from ServletContext objects. It allows to be instanced with a
14  * 'prefix' that will be added in front of all attributes.
15  */

16 public class ServletContextBeanLoader implements BeanLoader {
17
18     public ServletContextBeanLoader() {
19     }
20
21     String JavaDoc prefix = null;
22
23     public ServletContextBeanLoader(String JavaDoc prefix) {
24         this.prefix = prefix;
25     }
26
27     public static void loadBean(Object JavaDoc bean, Object JavaDoc context, String JavaDoc prefix) {
28         if (context instanceof ServletContext JavaDoc) {
29
30             Enumeration JavaDoc attribNames = ((ServletContext JavaDoc)context).getAttributeNames();
31             while (attribNames.hasMoreElements()) {
32                 String JavaDoc attribName = (String JavaDoc) attribNames.nextElement();
33                 Object JavaDoc value = ((ServletContext JavaDoc)context).getAttribute(attribName);
34                 if (value == null) {
35                     continue;
36                 }
37                 if (prefix != null) {
38                     attribName = prefix + Character.toUpperCase(attribName.charAt(0)) + attribName.substring(1);
39                 }
40                 try {
41                     BeanUtil.setPropertyForcedSilent(bean, attribName, value);
42                 } catch (BeanException bex) {
43                     // ignore exception
44
}
45             }
46         }
47     }
48
49     public void load(Object JavaDoc bean, Object JavaDoc context) {
50         loadBean(bean, context, prefix);
51     }
52
53 }
54
Popular Tags