1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.struts2.components;
19
20 import java.util.Map;
21
22 import javax.servlet.http.HttpServletRequest;
23 import javax.servlet.http.HttpServletResponse;
24
25 import org.apache.struts2.util.TokenHelper;
26
27 import com.opensymphony.xwork2.util.ValueStack;
28
29 /***
30 * <!-- START SNIPPET: javadoc -->
31 * Stop double-submission of forms.</p>
32 *
33 * The token tag is used to help with the "double click" submission problem. It is needed if you are using the
34 * TokenInterceptor or the TokenSessionInterceptor. The s:token tag merely places a hidden element that contains
35 * the unique token.</p>
36 * <!-- END SNIPPET: javadoc -->
37 *
38 * <p/> <b>Examples</b>
39 *
40 * <pre>
41 * <!-- START SNIPPET: example -->
42 * <s:token />
43 * <!-- END SNIPPET: example -->
44 * </pre>
45 *
46 * @see org.apache.struts2.interceptor.TokenInterceptor
47 * @see org.apache.struts2.interceptor.TokenSessionStoreInterceptor
48 *
49 * @s.tag name="token" tld-body-content="JSP" tld-tag-class="org.apache.struts2.views.jsp.ui.TokenTag"
50 * description="Stop double-submission of forms"
51 */
52 public class Token extends UIBean {
53
54 public static final String TEMPLATE = "token";
55
56 public Token(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
57 super(stack, request, response);
58 }
59
60 protected String getDefaultTemplate() {
61 return TEMPLATE;
62 }
63
64 /***
65 * First looks for the token in the PageContext using the supplied name (or {@link org.apache.struts2.util.TokenHelper#DEFAULT_TOKEN_NAME}
66 * if no name is provided) so that the same token can be re-used for the scope of a request for the same name. If
67 * the token is not in the PageContext, a new Token is created and set into the Session and the PageContext with
68 * the name.
69 */
70 protected void evaluateExtraParams() {
71 super.evaluateExtraParams();
72
73 String tokenName;
74 Map parameters = getParameters();
75
76 if (parameters.containsKey("name")) {
77 tokenName = (String) parameters.get("name");
78 } else {
79 if (name == null) {
80 tokenName = TokenHelper.DEFAULT_TOKEN_NAME;
81 } else {
82 tokenName = findString(name);
83
84 if (tokenName == null) {
85 tokenName = name;
86 }
87 }
88
89 addParameter("name", tokenName);
90 }
91
92 String token = buildToken(tokenName);
93 addParameter("token", token);
94 addParameter("tokenNameField", TokenHelper.TOKEN_NAME_FIELD);
95 }
96
97 /***
98 * This will be removed in a future version of Struts.
99 * @deprecated Templates should use $parameters from now on, not $tag.
100 */
101 public String getTokenNameField() {
102 return TokenHelper.TOKEN_NAME_FIELD;
103 }
104
105 private String buildToken(String name) {
106 Map context = stack.getContext();
107 Object myToken = context.get(name);
108
109 if (myToken == null) {
110 myToken = TokenHelper.setToken(name);
111 context.put(name, myToken);
112 }
113
114 return myToken.toString();
115 }
116 }