Jackie
Jackie

Reputation: 23607

How to handle Data Mapping from page to Servlet

So here is the deal I have a set of attributes that are check boxes. Both are HTML checkboxes, but one is checked=true where as the otherone is checked = 1. (Wasn't sure how to escape so the out of place quotes are just for show)

"<"input type="checkbox" class="attribute" name="trueFalse" value="true"/>

"<"input type="checkbox" class="attribute" name"oneZero" value="1"/>

The problem comes in when they are not checked, there is no way I can find to pass a false or 0, instead the request property just doesn't exist. So I am trying to find the best way to handle this, so far I have come up with...

  1. Use JS and set a hidden instead of the actual textbox -I don't want to do this because then for each new attribute I need to edit the JS
  2. Add an enum with a default value
  3. Create some sort of filter

Anyone have better ideas or a fan of one option?

Processing code is as follows

public Map<Utils.Attributes, String> getAttributesFromRequest(HttpServletRequest request, String postfix, String prefix){
    Map<Utils.Attributes, String> returnValue = new HashMap<Utils.Attributes, String>();
    for (Utils.Attributes attr : Utils.Attributes.values()) {
        StringBuilder sb = new StringBuilder();
        sb.append(prefix);
        sb.append(attr.getName());
        sb.append(prefix);
        String value = request.getParameter(sb.toString());
        if(testValue(value)){
            returnValue.put(attr, value);
        }
    }
    return returnValue;
}

Upvotes: 0

Views: 85

Answers (1)

JB Nizet
JB Nizet

Reputation: 692121

Why don't you just put default values in the map (false and 0), and override them with the values from the request parameters if they are present?

Upvotes: 2

Related Questions