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