KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > servlet > tags > form > TagIdGenerator


1 /*
2  * Copyright 2002-2006 the original author or authors.
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, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.servlet.tags.form;
18
19 import javax.servlet.jsp.PageContext JavaDoc;
20
21 /**
22  * Utility class for generating '<code>id</code>' attributes values for JSP tags. Given the
23  * name of a tag (the data bound path in most cases) returns a unique ID for that name within
24  * the current {@link PageContext}. Each request for an ID for a given name will append an
25  * ever increasing counter to the name itself. For instance, given the name '<code>person.name</code>',
26  * the first request will give '<code>person.name1</code>' and the second will give
27  * '<code>person.name1</code>'. This supports the common use case where a set of radio or check buttons
28  * are generated for the same data field, with each button being a distinct tag instance.
29  *
30  * @author Rob Harrop
31  * @since 2.0
32  */

33 final class TagIdGenerator {
34
35     /**
36      * The prefix for all {@link PageContext} attributes created by this tag.
37      */

38     private static final String JavaDoc PAGE_CONTEXT_ATTRIBUTE_PREFIX = TagIdGenerator.class.getName();
39
40     /**
41      * Cannot create externally.
42      */

43     private TagIdGenerator() {
44
45     }
46
47     /**
48      * Gets the next unique ID (withing the given {@link PageContext}) for the supplied name.
49      */

50     public static String JavaDoc nextId(String JavaDoc name, PageContext JavaDoc pageContext) {
51         String JavaDoc attributeName = PAGE_CONTEXT_ATTRIBUTE_PREFIX + "." + name;
52         Integer JavaDoc currentCount = (Integer JavaDoc) pageContext.getAttribute(attributeName);
53         currentCount = (currentCount == null ? new Integer JavaDoc(1) : new Integer JavaDoc(currentCount.intValue() + 1));
54         pageContext.setAttribute(attributeName, currentCount);
55         return name + currentCount.intValue();
56     }
57 }
58
Popular Tags