001/*
002 * Copyright 2002-2015 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.servlet.tags;
018
019import javax.servlet.jsp.JspException;
020import javax.servlet.jsp.tagext.BodyTagSupport;
021
022/**
023 * JSP tag for collecting name-value parameters and passing them to a
024 * {@link ParamAware} ancestor in the tag hierarchy.
025 *
026 * <p>This tag must be nested under a param aware tag.
027 *
028 * @author Scott Andrews
029 * @author Nicholas Williams
030 * @since 3.0
031 * @see Param
032 * @see UrlTag
033 */
034@SuppressWarnings("serial")
035public class ParamTag extends BodyTagSupport {
036
037        private String name;
038
039        private String value;
040
041        private boolean valueSet;
042
043
044        /**
045         * Set the name of the parameter (required).
046         */
047        public void setName(String name) {
048                this.name = name;
049        }
050
051        /**
052         * Set the value of the parameter (optional).
053         */
054        public void setValue(String value) {
055                this.value = value;
056                this.valueSet = true;
057        }
058
059
060        @Override
061        public int doEndTag() throws JspException {
062                Param param = new Param();
063                param.setName(this.name);
064                if (this.valueSet) {
065                        param.setValue(this.value);
066                }
067                else if (getBodyContent() != null) {
068                        // Get the value from the tag body
069                        param.setValue(getBodyContent().getString().trim());
070                }
071
072                // Find a param aware ancestor
073                ParamAware paramAwareTag = (ParamAware) findAncestorWithClass(this, ParamAware.class);
074                if (paramAwareTag == null) {
075                        throw new JspException("The param tag must be a descendant of a tag that supports parameters");
076                }
077
078                paramAwareTag.addParam(param);
079
080                return EVAL_PAGE;
081        }
082
083        @Override
084        public void release() {
085                super.release();
086                this.name = null;
087                this.value = null;
088                this.valueSet = false;
089        }
090
091}