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