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.internal.controller.ThreadContext;
22  import org.seasar.cubby.internal.util.TokenHelper;
23  import org.seasar.cubby.tags.TokenTag;
24  import org.seasar.cubby.validator.ArrayFieldValidator;
25  import org.seasar.cubby.validator.MessageHelper;
26  import org.seasar.cubby.validator.ValidationContext;
27  
28  /**
29   * 2重サブミットの検証をします。
30   * <p>
31   * ポストする画面で{@link TokenTag}を使用して、Actionクラスで TokenValidatorを使用することで、
32   * 2重サブミットを防止します。
33   * </p>
34   * <p>
35   * デフォルトエラーメッセージキー:valid.token
36   * </p>
37   * 
38   * @author agata
39   * @author baba
40   * @since 1.0.0
41   */
42  public class TokenValidator implements ArrayFieldValidator {
43  
44  	/**
45  	 * メッセージヘルパ。
46  	 */
47  	private final MessageHelper messageHelper;
48  
49  	/**
50  	 * コンストラクタ。
51  	 */
52  	public TokenValidator() {
53  		this("valid.token");
54  	}
55  
56  	/**
57  	 * エラーメッセージキーを指定するコンストラクタ
58  	 * 
59  	 * @param messageKey
60  	 *            エラーメッセージキー
61  	 */
62  	public TokenValidator(final String messageKey) {
63  		this.messageHelper = new MessageHelper(messageKey);
64  	}
65  
66  	/**
67  	 * {@inheritDoc}
68  	 */
69  	public void validate(final ValidationContext context, final Object[] values) {
70  		if (values == null) {
71  			return;
72  		}
73  		if (values.length != 1) {
74  			context.addMessageInfo(this.messageHelper.createMessageInfo());
75  		} else {
76  			final String token = (String) values[0];
77  			final HttpServletRequest request = ThreadContext.getRequest();
78  			final HttpSession session = request.getSession(false);
79  			if (session != null) {
80  				if (!TokenHelper.validateToken(session, token)) {
81  					context.addMessageInfo(this.messageHelper
82  							.createMessageInfo());
83  				}
84  			}
85  		}
86  	}
87  }