1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.struts2.interceptor;
23
24 import com.opensymphony.xwork2.ActionInvocation;
25 import com.opensymphony.xwork2.util.logging.Logger;
26 import com.opensymphony.xwork2.util.logging.LoggerFactory;
27 import com.opensymphony.xwork2.interceptor.Interceptor;
28
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.HashMap;
32 import java.util.Iterator;
33
34 /***
35 * <!-- START SNIPPET: description -->
36 * Looks for a hidden identification field that specifies the original value of the checkbox.
37 * If the checkbox isn't submitted, insert it into the parameters as if it was with the value
38 * of 'false'.
39 * <!-- END SNIPPET: description -->
40 * <p/>
41 * <!-- START SNIPPET: parameters -->
42 * <ul><li>setUncheckedValue -
43 * The default value of an unchecked box can be overridden by setting the 'uncheckedValue' property.
44 * </li></ul>
45 * <!-- END SNIPPET: parameters -->
46 * <p/>
47 * <!-- START SNIPPET: extending -->
48 * <p/>
49 * <!-- END SNIPPET: extending -->
50 */
51 public class CheckboxInterceptor implements Interceptor {
52
53 /*** Auto-generated serialization id */
54 private static final long serialVersionUID = -586878104807229585L;
55
56 private String uncheckedValue = Boolean.FALSE.toString();
57
58 private static final Logger LOG = LoggerFactory.getLogger(CheckboxInterceptor.class);
59
60 public void destroy() {
61 }
62
63 public void init() {
64 }
65
66 public String intercept(ActionInvocation ai) throws Exception {
67 Map parameters = ai.getInvocationContext().getParameters();
68 Map<String, String[]> newParams = new HashMap<String, String[]>();
69 Set<Map.Entry> entries = parameters.entrySet();
70 for (Iterator<Map.Entry> iterator = entries.iterator(); iterator.hasNext();) {
71 Map.Entry entry = iterator.next();
72 String key = (String)entry.getKey();
73
74 if (key.startsWith("__checkbox_")) {
75 String name = key.substring("__checkbox_".length());
76
77 Object values = entry.getValue();
78 iterator.remove();
79 if (values != null && values instanceof String[] && ((String[])values).length > 1) {
80 LOG.debug("Bypassing automatic checkbox detection due to multiple checkboxes of the same name: #1", name);
81 continue;
82 }
83
84
85 if (!parameters.containsKey(name)) {
86
87 newParams.put(name, new String[]{uncheckedValue});
88 }
89 }
90 }
91
92 parameters.putAll(newParams);
93
94 return ai.invoke();
95 }
96
97 /***
98 * Overrides the default value for an unchecked checkbox
99 *
100 * @param uncheckedValue The uncheckedValue to set
101 */
102 public void setUncheckedValue(String uncheckedValue) {
103 this.uncheckedValue = uncheckedValue;
104 }
105 }