简体   繁体   中英

JSTL c:set a bean property with an array, wrong setter method being called

So I am using <c:set> to set the value of an object. The problem is there are two setter methods with the same name, the wrong one is being called.

In my JSP i have this:

<c:when test="${not empty paramValues.tag }">
    <c:set target="${listing }" property="tags" value="${paramValues.tag }" />
</c:when>

Now, we know that ${paramValues.tag} is a string array as defined here ( http://docs.oracle.com/javaee/1.3/api/javax/servlet/ServletRequest.html#getParameterValues(java.lang.String) ). I have verified this by outputting ${paramValues.tag} and was able to iterate over the values using a foreach loop <c:forEach var="test" items="${paramValues.tag}">

In my java class i have the following:

public void setTags(final String tagName) {
    LOG.debug("Setting tags from single tag string");
    this.setTags(Arrays.asList(tagName));
}

public void setTags(final String[] tagNames) {
    LOG.debug("Settings tags from tag array");
    this.setTags(Arrays.asList(tagNames));
}

The result i am seeing is that the log message "Setting tags from a single tag string" is called. So c:set is calling the setTags(String) method not the setTags(String[]) method. The "tagName" parameter that is passed is along the lines of "[Ljava.lang.String;@73f9e088"

Why would it do this? Have i done something wrong?

Thanks for your input.

The concept of a "property" is that you have a getter and setter where the return type of the getter is the same as the argument type of the setter.

So in this case the "property inspector" probably deduces a property tagNames being of the type String and not String[], the fact that there is also a setter with an array of Strings doesn't matter.

Suggestion: introduce a setTag accepting a String and setTags accepting an array of Strings.

Note, the property concept does NOT require an attribute: in this case the setTag could be implemented as

public void setTag(String tag) {
    setTags(new String[] { tag, });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM