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<String> keys = parameters.keySet();
70 for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {
71 String key = iterator.next();
72
73 if (key.startsWith("__checkbox_")) {
74 String name = key.substring("__checkbox_".length());
75
76 Object values = parameters.get(key);
77 iterator.remove();
78 if (values != null && values instanceof String[] && ((String[])values).length > 1) {
79 LOG.debug("Bypassing automatic checkbox detection due to multiple checkboxes of the same name: #1", name);
80 continue;
81 }
82
83
84 if (!parameters.containsKey(name)) {
85
86 newParams.put(name, new String[]{uncheckedValue});
87 }
88 }
89 }
90
91 parameters.putAll(newParams);
92
93 return ai.invoke();
94 }
95
96 /***
97 * Overrides the default value for an unchecked checkbox
98 *
99 * @param uncheckedValue The uncheckedValue to set
100 */
101 public void setUncheckedValue(String uncheckedValue) {
102 this.uncheckedValue = uncheckedValue;
103 }
104 }