View Javadoc

1   /*
2    * Copyright 2004-2009 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.seasar.cubby.validator.validators;
17  
18  import javax.servlet.http.HttpServletRequest;
19  import javax.servlet.http.HttpSession;
20  
21  import org.seasar.cubby.action.MessageInfo;
22  import org.seasar.cubby.internal.controller.ThreadContext;
23  import org.seasar.cubby.internal.util.TokenHelper;
24  import org.seasar.cubby.tags.TokenTag;
25  import org.seasar.cubby.validator.ArrayFieldValidator;
26  import org.seasar.cubby.validator.ValidationContext;
27  
28  /**
29   * 2 重サブミットの検証をします。
30   * <p>
31   * ポストする画面で {@link TokenTag} を使用し、アクションクラスでこのクラスで検証することで 2 重サブミットを防止します。
32   * </p>
33   * <p>
34   * <table>
35   * <caption>検証エラー時に設定するエラーメッセージ</caption> <tbody>
36   * <tr>
37   * <th scope="row">デフォルトのキー</th>
38   * <td>valid.token</td>
39   * </tr>
40   * <tr>
41   * <th scope="row">置換文字列</th>
42   * <td>
43   * <ol start="0">
44   * <li>フィールド名</li>
45   * </ol></td>
46   * </tr>
47   * </tbody>
48   * </table>
49   * </p>
50   * 
51   * @author agata
52   * @author baba
53   */
54  public class TokenValidator implements ArrayFieldValidator {
55  
56  	/**
57  	 * メッセージキー。
58  	 */
59  	private final String messageKey;
60  
61  	/**
62  	 * コンストラクタ。
63  	 */
64  	public TokenValidator() {
65  		this("valid.token");
66  	}
67  
68  	/**
69  	 * エラーメッセージキーを指定するコンストラクタ
70  	 * 
71  	 * @param messageKey
72  	 *            エラーメッセージキー
73  	 */
74  	public TokenValidator(final String messageKey) {
75  		this.messageKey = messageKey;
76  	}
77  
78  	/**
79  	 * {@inheritDoc}
80  	 */
81  	public void validate(final ValidationContext context, final Object[] values) {
82  		if (values == null) {
83  			return;
84  		}
85  
86  		if (values.length == 1) {
87  			final String token = (String) values[0];
88  			final HttpServletRequest request = ThreadContext.getRequest();
89  			final HttpSession session = request.getSession(false);
90  			if (session == null) {
91  				return;
92  			}
93  			if (TokenHelper.validateToken(session, token)) {
94  				return;
95  			}
96  		}
97  
98  		final MessageInfo messageInfo = new MessageInfo();
99  		messageInfo.setKey(this.messageKey);
100 		context.addMessageInfo(messageInfo);
101 	}
102 }