1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.struts.scripting;
19
20
21 import java.util.Enumeration;
22 import java.util.Properties;
23
24
25 import org.apache.commons.logging.Log;
26 import org.apache.commons.logging.LogFactory;
27
28
29 import javax.servlet.http.HttpServletRequest;
30 import org.apache.bsf.BSFException;
31 import org.apache.bsf.BSFManager;
32
33
34 /***
35 * Takes request parameters and declares variables with them. If a variable is
36 * already exists with that name, a "_" is prepended to the name. Both Strings
37 * and arrays are recognized.
38 */
39 public class RequestToVariableFilter implements BSFManagerFilter {
40
41 /*** The logging instance. */
42 private static final Log LOG = LogFactory.getLog(TestFilter.class);
43
44
45 /***
46 * Initializes the filter.
47 *
48 *@param name The name of the filter
49 *@param props The properties
50 */
51 public void init(String name, Properties props) { }
52
53
54 /***
55 * Applies the filter.
56 *
57 *@param mgr The bsf manager
58 *@return The bsf manager
59 */
60 public BSFManager apply(BSFManager mgr) {
61 HttpServletRequest request =
62 (HttpServletRequest) mgr.lookupBean("request");
63 String[] values = null;
64 String name = null;
65 String newName = null;
66 Object o = null;
67 for (Enumeration e = request.getParameterNames();
68 e.hasMoreElements();) {
69 name = (String) e.nextElement();
70 o = mgr.lookupBean(name);
71 if (o == null) {
72 newName = name;
73 } else {
74 newName = "_" + name;
75 }
76
77 values = request.getParameterValues(name);
78 try {
79 if (values.length > 1) {
80 mgr.declareBean(newName, values, values.getClass());
81 if (LOG.isDebugEnabled()) {
82 LOG.debug("creating array var " + newName);
83 }
84 } else {
85 mgr.declareBean(newName, values[0], String.class);
86 if (LOG.isDebugEnabled()) {
87 LOG.debug("creating string var " + newName);
88 }
89 }
90 } catch (BSFException ex) {
91 LOG.warn("Unable to set variable " + newName, ex);
92 }
93
94 }
95 if (LOG.isDebugEnabled()) {
96 LOG.debug("Done filtering");
97 }
98 return mgr;
99 }
100 }
101