Why doesn’t an empty field reset my bean property?

As you explained in When can a parameter value be null?, an empty text form field value is typically sent to a JSP (or servlet) page as an empty string parameter value.But a String property in my bean corresponding to a text field does not get set to an empty string when I use the setProperty action. What’s going on?
Answer:
I describe this in Chapter 15 in the book, in the section Unexpected <jsp:setProperty> Behavior.To match the behavior for properties corresponding to checkboxes, radio buttons and selection lists, the JSP specification says that if a parameter value is an empty string, the corresponding property setter method should notbe called. So when you use

<jsp:setProperty name="foo" property="*" />

for a bean with properties corresponding to various types of form elements, an empty text field has the same effect as a checkbox that is not checked; the property is not set at all.

If you use a bean to capture form input and you want to reset a property when the user clears the corresponding form field, you can use this work-around. First create a method in the bean that resets all properties:

public void setReset(String ignored) {
  myFirstProperty = null;
  mySecondProperty = null;
  ...
}

Now you can invoke this method before you set the properties based on the current form field values in your JSP page:

<jsp:setProperty name="foo" property="reset" value="dummy"/>
<jsp:setProperty name="foo" property="*" />

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>